mirror of
https://hubproxy.babadafafafafa.cn/https://github.com/usestrix/strix.git
synced 2026-09-21 00:23:52 +08:00
Compare commits
1 Commits
docs/trim-
...
fix/tui-se
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19ec5fbf25 |
@@ -1,6 +1,3 @@
|
||||
# Built viewer bundles are generated output, not hand-edited source.
|
||||
exclude: ^strix/interface/viewer/static/assets/
|
||||
|
||||
repos:
|
||||
# Ruff for fast linting and formatting
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
@@ -12,18 +9,21 @@ repos:
|
||||
- id: ruff-format
|
||||
name: ruff-format
|
||||
|
||||
# MyPy for static type checking. Runs the project's own mypy from the uv
|
||||
# environment (`make dev-install`) so it sees the same dependencies and
|
||||
# stubs as `make check-all`.
|
||||
- repo: local
|
||||
# MyPy for static type checking
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v1.17.1
|
||||
hooks:
|
||||
- id: mypy
|
||||
name: mypy
|
||||
entry: uv run mypy
|
||||
language: system
|
||||
types_or: [python, pyi]
|
||||
files: ^(strix|tests)/
|
||||
require_serial: true
|
||||
additional_dependencies: [
|
||||
types-requests,
|
||||
types-python-dateutil,
|
||||
pydantic,
|
||||
fastapi,
|
||||
pytest,
|
||||
hatchling,
|
||||
"openai-agents[litellm]>=0.19.0,<0.20",
|
||||
]
|
||||
args: [--install-types, --non-interactive]
|
||||
|
||||
# Built-in hooks for basic file checks
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
@@ -62,6 +62,5 @@ ci:
|
||||
autoupdate_branch: ""
|
||||
autoupdate_commit_msg: "[pre-commit.ci] pre-commit autoupdate"
|
||||
autoupdate_schedule: weekly
|
||||
# pre-commit.ci cannot run `language: system` hooks; mypy runs via `make check-all`.
|
||||
skip: [mypy]
|
||||
skip: []
|
||||
submodules: false
|
||||
|
||||
@@ -28,7 +28,7 @@ Target-specific workflows built on the same engine:
|
||||
- **Open-source CLI (self-hosted):** free, fully local, BYO LLM key, needs Docker. Best for local dev loops, air-gapped/offline, and full control.
|
||||
```bash
|
||||
curl -sSL https://strix.ai/install | bash # install
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3" # any LiteLLM model id
|
||||
export STRIX_LLM="openai/gpt-5.4" # any LiteLLM model id
|
||||
export LLM_API_KEY="<key>"
|
||||
strix -n -t ./ --scan-mode quick --max-budget 10 # headless scan; always use -n
|
||||
```
|
||||
|
||||
@@ -31,7 +31,7 @@ Thank you for your interest in contributing to Strix! This guide will help you g
|
||||
|
||||
3. **Configure your LLM provider**
|
||||
```bash
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
export LLM_API_KEY="your-api-key"
|
||||
```
|
||||
|
||||
|
||||
174
README.md
174
README.md
@@ -82,7 +82,7 @@ Strix are autonomous AI penetration testing agents that act just like real hacke
|
||||
curl -sSL https://strix.ai/install | bash
|
||||
|
||||
# Configure your AI provider
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
export LLM_API_KEY="your-api-key"
|
||||
|
||||
# Run your first security assessment
|
||||
@@ -172,9 +172,18 @@ strix view my-run-name
|
||||
strix view --host 0.0.0.0 --port 8080 --no-open
|
||||
```
|
||||
|
||||
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.
|
||||
`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.
|
||||
|
||||
See the [viewer documentation](https://docs.strix.ai/usage/viewer) for the options and for reaching the viewer from another machine.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -200,9 +209,18 @@ 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, Postman export, or a live collection by id
|
||||
# OpenAPI / Swagger file (.json / .yaml)
|
||||
strix --target ./openapi.yaml --target https://api.your-app.com
|
||||
strix --target postman://<collection-uuid> --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>"
|
||||
```
|
||||
|
||||
|
||||
@@ -217,9 +235,19 @@ 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
|
||||
```
|
||||
|
||||
See the [CLI reference](https://docs.strix.ai/usage/cli) for every option, including scan modes, diff scope, instruction files, and budgets.
|
||||
# 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
|
||||
```
|
||||
|
||||
### Headless Mode
|
||||
|
||||
@@ -259,56 +287,153 @@ jobs:
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> 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.
|
||||
> 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.
|
||||
|
||||
### Configuration
|
||||
|
||||
```bash
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
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 auth status # show the active sign-in, or logout to forget it
|
||||
strix --target ./app-directory
|
||||
|
||||
strix auth status # show the active sign-in
|
||||
strix auth logout # forget the sign-in
|
||||
```
|
||||
|
||||
#### Use the managed platform: `strix cloud`
|
||||
|
||||
Run scans on [app.strix.ai](https://app.strix.ai) from the terminal, without Docker or an LLM key:
|
||||
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`:
|
||||
|
||||
```bash
|
||||
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 vulns list --severity critical
|
||||
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
|
||||
```
|
||||
|
||||
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.
|
||||
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`.
|
||||
|
||||
See the [cloud CLI documentation](https://docs.strix.ai/cloud/cli) for scopes, workspaces, billing, and source-upload options.
|
||||
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 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:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
#### 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 local `stdio` servers or remote `http` 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:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"name": "local_fs",
|
||||
"transport": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
|
||||
},
|
||||
{
|
||||
"name": "github",
|
||||
"transport": "http",
|
||||
@@ -319,16 +444,13 @@ Strix can connect to Model Context Protocol (MCP) servers you list and expose th
|
||||
]
|
||||
```
|
||||
|
||||
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.
|
||||
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`.
|
||||
|
||||
**Recommended models for best results:**
|
||||
|
||||
- [Z.ai GLM-5.3 on OpenRouter](https://openrouter.ai/z-ai/glm-5.3) - `openrouter/z-ai/glm-5.3` (the default pick)
|
||||
- [OpenAI GPT-5.4](https://openai.com/api/) - `openai/gpt-5.4`
|
||||
- [Anthropic Claude Sonnet 4.6](https://claude.com/platform/api) - `anthropic/claude-sonnet-4-6`
|
||||
- [Google Gemini 3 Pro Preview](https://cloud.google.com/vertex-ai) - `vertex_ai/gemini-3-pro-preview`
|
||||
- [DeepSeek V4 Pro](https://platform.deepseek.com) - `deepseek/deepseek-v4-pro`
|
||||
- [Moonshot Kimi K3](https://platform.kimi.ai) - `moonshot/kimi-k3`
|
||||
|
||||
See the [LLM Providers documentation](https://docs.strix.ai/llm-providers/overview) for all supported providers including Vertex AI, Bedrock, Azure, and local models.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Configure Strix using environment variables or a config file.
|
||||
## LLM Configuration
|
||||
|
||||
<ParamField path="STRIX_LLM" type="string" required>
|
||||
Model name in LiteLLM format (e.g., `openrouter/z-ai/glm-5.3`, `openai/gpt-5.4`).
|
||||
Model name in LiteLLM format (e.g., `openai/gpt-5.4`, `anthropic/claude-sonnet-4-6`).
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="LLM_API_KEY" type="string">
|
||||
@@ -145,7 +145,7 @@ strix --target ./app --config /path/to/config.json
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"STRIX_LLM": "openrouter/z-ai/glm-5.3",
|
||||
"STRIX_LLM": "openai/gpt-5.4",
|
||||
"LLM_API_KEY": "sk-...",
|
||||
"STRIX_REASONING_EFFORT": "high"
|
||||
}
|
||||
@@ -156,7 +156,7 @@ strix --target ./app --config /path/to/config.json
|
||||
|
||||
```bash
|
||||
# Required
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
export LLM_API_KEY="sk-..."
|
||||
|
||||
# Optional: Enable web search
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
---
|
||||
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
|
||||
```
|
||||
@@ -33,7 +33,7 @@ description: "Contribute to Strix development"
|
||||
</Step>
|
||||
<Step title="Configure LLM">
|
||||
```bash
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
export LLM_API_KEY="your-api-key"
|
||||
```
|
||||
</Step>
|
||||
|
||||
@@ -25,8 +25,7 @@
|
||||
"pages": [
|
||||
"usage/cli",
|
||||
"usage/scan-modes",
|
||||
"usage/instructions",
|
||||
"usage/viewer"
|
||||
"usage/instructions"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -78,8 +77,7 @@
|
||||
{
|
||||
"group": "Strix Cloud",
|
||||
"pages": [
|
||||
"cloud/overview",
|
||||
"cloud/cli"
|
||||
"cloud/overview"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -78,7 +78,7 @@ Strix uses a graph of specialized agents for comprehensive security testing:
|
||||
curl -sSL https://strix.ai/install | bash
|
||||
|
||||
# Configure
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
export LLM_API_KEY="your-api-key"
|
||||
|
||||
# Scan
|
||||
|
||||
@@ -37,7 +37,7 @@ Add these secrets to your repository:
|
||||
|
||||
| Secret | Description |
|
||||
|--------|-------------|
|
||||
| `STRIX_LLM` | Model name (e.g., `openrouter/z-ai/glm-5.3`) |
|
||||
| `STRIX_LLM` | Model name (e.g., `openai/gpt-5.4`) |
|
||||
| `LLM_API_KEY` | API key for your LLM provider |
|
||||
|
||||
## Exit Codes
|
||||
|
||||
@@ -17,9 +17,6 @@ export LLM_API_BASE="https://api.novita.ai/openai"
|
||||
|
||||
| Model | Configuration |
|
||||
|-------|---------------|
|
||||
| GLM-5.3 | `openai/zai-org/glm-5.3` |
|
||||
| Kimi K3 | `openai/moonshotai/kimi-k3` |
|
||||
| DeepSeek V4 Pro | `openai/deepseek/deepseek-v4-pro` |
|
||||
| Kimi K2.5 | `openai/moonshotai/kimi-k2.5` |
|
||||
| GLM-5 | `openai/zai-org/glm-5` |
|
||||
| MiniMax M2.5 | `openai/minimax/minimax-m2.5` |
|
||||
|
||||
@@ -8,7 +8,7 @@ description: "Configure Strix with models via OpenRouter"
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openrouter/openai/gpt-5.4"
|
||||
export LLM_API_KEY="sk-or-..."
|
||||
```
|
||||
|
||||
@@ -18,12 +18,9 @@ Access any model on OpenRouter using the format `openrouter/<provider>/<model>`:
|
||||
|
||||
| Model | Configuration |
|
||||
|-------|---------------|
|
||||
| GLM-5.3 (default) | `openrouter/z-ai/glm-5.3` |
|
||||
| GPT-5.4 | `openrouter/openai/gpt-5.4` |
|
||||
| Claude Sonnet 4.6 | `openrouter/anthropic/claude-sonnet-4.6` |
|
||||
| Gemini 3 Pro | `openrouter/google/gemini-3-pro-preview` |
|
||||
| DeepSeek V4 Pro | `openrouter/deepseek/deepseek-v4-pro` |
|
||||
| Kimi K3 | `openrouter/moonshotai/kimi-k3` |
|
||||
| GLM-4.7 | `openrouter/z-ai/glm-4.7` |
|
||||
|
||||
## Get API Key
|
||||
|
||||
@@ -9,17 +9,14 @@ Strix uses [LiteLLM](https://docs.litellm.ai/docs/providers) for model compatibi
|
||||
|
||||
Set your model and API key:
|
||||
|
||||
| Model | Provider | Configuration |
|
||||
| -------------------- | ----------------- | -------------------------------- |
|
||||
| GLM-5.3 (default) | Z.ai (OpenRouter) | `openrouter/z-ai/glm-5.3` |
|
||||
| GPT-5.4 | OpenAI | `openai/gpt-5.4` |
|
||||
| Claude Sonnet 4.6 | Anthropic | `anthropic/claude-sonnet-4-6` |
|
||||
| Gemini 3 Pro | Google Vertex | `vertex_ai/gemini-3-pro-preview` |
|
||||
| DeepSeek V4 Pro | DeepSeek | `deepseek/deepseek-v4-pro` |
|
||||
| Kimi K3 | Moonshot | `moonshot/kimi-k3` |
|
||||
| Model | Provider | Configuration |
|
||||
| ----------------- | ------------- | -------------------------------- |
|
||||
| GPT-5.4 | OpenAI | `openai/gpt-5.4` |
|
||||
| Claude Sonnet 4.6 | Anthropic | `anthropic/claude-sonnet-4-6` |
|
||||
| Gemini 3 Pro | Google Vertex | `vertex_ai/gemini-3-pro-preview` |
|
||||
|
||||
```bash
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
export LLM_API_KEY="your-api-key"
|
||||
```
|
||||
|
||||
@@ -65,7 +62,6 @@ See the [Local Models guide](/llm-providers/local) for setup instructions and re
|
||||
Use LiteLLM's `provider/model-name` format:
|
||||
|
||||
```
|
||||
openrouter/z-ai/glm-5.3
|
||||
openai/gpt-5.4
|
||||
anthropic/claude-sonnet-4-6
|
||||
vertex_ai/gemini-3-pro-preview
|
||||
|
||||
@@ -28,12 +28,12 @@ description: "Install Strix and run your first security scan"
|
||||
Set your LLM provider:
|
||||
|
||||
```bash
|
||||
export STRIX_LLM="openrouter/z-ai/glm-5.3"
|
||||
export STRIX_LLM="openai/gpt-5.4"
|
||||
export LLM_API_KEY="your-api-key"
|
||||
```
|
||||
|
||||
<Tip>
|
||||
For best results, use `openrouter/z-ai/glm-5.3` (the default pick), `openai/gpt-5.4`, `anthropic/claude-opus-4-6`, or `openai/gpt-5.2`.
|
||||
For best results, use `openai/gpt-5.4`, `anthropic/claude-opus-4-6`, or `openai/gpt-5.2`.
|
||||
</Tip>
|
||||
|
||||
## Run Your First Scan
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
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.
|
||||
@@ -250,7 +250,6 @@ ignore = [
|
||||
# Stdlib HTTP handler overrides (do_GET/do_POST) and lazy imports that avoid a
|
||||
# circular dependency with strix.telemetry / strix.interface.viewer.report_pdf.
|
||||
"strix/interface/viewer/server.py" = ["N802", "PLC0415"]
|
||||
"strix/interface/cloud/payment_proxy.py" = ["N802"]
|
||||
# Lazy telemetry import to avoid importing PostHog before the viewer starts.
|
||||
"strix/interface/viewer/cli.py" = ["PLC0415"]
|
||||
# Lazy imports inside functions to avoid circular dependency with
|
||||
@@ -414,8 +413,6 @@ known_third_party = ["pydantic", "litellm"]
|
||||
# ============================================================================
|
||||
|
||||
[tool.bandit]
|
||||
# Tests are covered by ruff's flake8-bandit rules (see per-file-ignores above),
|
||||
# which is where fixture tokens and loopback URL opens are already waived.
|
||||
exclude_dirs = ["docs", "build", "dist", "tests"]
|
||||
exclude_dirs = ["docs", "build", "dist"]
|
||||
skips = ["B101", "B601", "B404", "B603", "B607"] # Skip assert, shell injection, subprocess import and partial path checks
|
||||
severity = "medium"
|
||||
|
||||
@@ -183,7 +183,7 @@ def build_authorize_url(challenge: str, state: str) -> str:
|
||||
"code_challenge": challenge,
|
||||
"code_challenge_method": "S256",
|
||||
"state": state,
|
||||
"id_token_add_organizations": "true", # nosec B105 - boolean flag, not a secret
|
||||
"id_token_add_organizations": "true",
|
||||
"codex_cli_simplified_flow": "true",
|
||||
"originator": ORIGINATOR,
|
||||
}
|
||||
|
||||
@@ -10,13 +10,11 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
from pydantic import AliasChoices, BaseModel
|
||||
|
||||
from strix.config.settings import LlmSettings, Settings
|
||||
from strix.config.settings import Settings
|
||||
from strix.utils.secret_files import write_secret_text
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
|
||||
from pydantic.fields import FieldInfo
|
||||
|
||||
|
||||
@@ -27,11 +25,6 @@ _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.
|
||||
@@ -61,31 +54,22 @@ def apply_config_override(path: Path) -> None:
|
||||
|
||||
|
||||
def persist_current() -> None:
|
||||
"""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.
|
||||
"""
|
||||
"""Write currently-set env vars to the active config file (0o600)."""
|
||||
s = load_settings()
|
||||
target = _override or _DEFAULT_PATH
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
env_block = _drop_stale_llm_connection(_read_env_block(target))
|
||||
for sub_name in type(s).model_fields:
|
||||
env_block: dict[str, str] = {}
|
||||
for sub_name in 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():
|
||||
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]
|
||||
for alias in _aliases_for(finfo):
|
||||
value = os.environ.get(alias.upper())
|
||||
if value:
|
||||
env_block[alias.upper()] = value
|
||||
break
|
||||
|
||||
write_secret_text(target, json.dumps({"env": env_block}, indent=2))
|
||||
|
||||
@@ -109,9 +93,17 @@ 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.
|
||||
"""
|
||||
env_block_upper = _drop_stale_llm_connection(_read_env_block(path))
|
||||
if not env_block_upper:
|
||||
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 {}
|
||||
|
||||
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]] = {}
|
||||
@@ -131,38 +123,3 @@ 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()}
|
||||
|
||||
@@ -562,8 +562,6 @@ DEFAULT_MODEL_RETRY = ModelRetrySettings(
|
||||
)
|
||||
|
||||
RECOMMENDED_MODEL_NAMES = (
|
||||
"zai/glm-5.3",
|
||||
"zai/glm-5.3-flash",
|
||||
"openai/gpt-5.6-sol",
|
||||
"openai/gpt-5.6-terra",
|
||||
"openai/gpt-5.6-luna",
|
||||
@@ -572,7 +570,6 @@ RECOMMENDED_MODEL_NAMES = (
|
||||
"openai/gpt-5.5",
|
||||
"openai/gpt-5.4",
|
||||
"openai/gpt-5.3-codex",
|
||||
"anthropic/claude-fable-5-1",
|
||||
"anthropic/claude-fable-5",
|
||||
"anthropic/claude-opus-5",
|
||||
"anthropic/claude-opus-4-8",
|
||||
@@ -580,8 +577,6 @@ RECOMMENDED_MODEL_NAMES = (
|
||||
"anthropic/claude-sonnet-4-6",
|
||||
"vertex_ai/gemini-3.1-pro-preview",
|
||||
"gemini/gemini-3.1-pro-preview",
|
||||
"vertex_ai/gemini-3.7-flash",
|
||||
"gemini/gemini-3.7-flash",
|
||||
"gemini/gemini-3.6-flash",
|
||||
"deepseek/deepseek-v4-pro",
|
||||
"deepseek/deepseek-v4-flash",
|
||||
@@ -603,7 +598,6 @@ FRONTIER_MODEL_FAMILIES = (
|
||||
(("deepseek",), ("deepseek-v4", "deepseek-r1", "deepseek-reasoner")),
|
||||
(("alibaba", "dashscope", "qwen"), ("qwen3.8", "qwen3.7", "qwen3-max")),
|
||||
(("moonshot", "moonshotai", "kimi"), ("kimi-k3", "kimi-k2.7", "kimi-k2.6")),
|
||||
(("zai", "z-ai", "zai-org", "zhipuai"), ("glm-5.3", "glm-5.2")),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -428,7 +428,6 @@ async def run_strix_scan(
|
||||
}
|
||||
for summary in mcp_registry.summaries()
|
||||
]
|
||||
|
||||
# Feed a non-secret connection roster (name / provider /
|
||||
# tool_count / dead) to two consumers: once now (all
|
||||
# currently healthy) and again whenever a connection later
|
||||
|
||||
@@ -14,7 +14,7 @@ import sys
|
||||
from rich.console import Console
|
||||
from rich.markup import escape
|
||||
|
||||
from strix.interface.cloud import http
|
||||
import strix.interface.cloud.http as http # noqa: PLR0402
|
||||
from strix.interface.cloud.render import json_mode
|
||||
from strix.interface.cloud.runner import resolve, run
|
||||
from strix.interface.cloud.session import run_session
|
||||
|
||||
@@ -70,7 +70,7 @@ def validate_environment() -> None:
|
||||
error_text.append("• ", style="white")
|
||||
error_text.append("STRIX_LLM", style="bold cyan")
|
||||
error_text.append(
|
||||
" - Model name to use (e.g., 'openrouter/z-ai/glm-5.3' or "
|
||||
" - Model name to use (e.g., 'openai/gpt-5.4' or "
|
||||
"'anthropic/claude-opus-4-7')\n",
|
||||
style="white",
|
||||
)
|
||||
@@ -102,7 +102,7 @@ def validate_environment() -> None:
|
||||
)
|
||||
|
||||
error_text.append("\nExample setup:\n", style="white")
|
||||
error_text.append("export STRIX_LLM='openrouter/z-ai/glm-5.3'\n", style="dim white")
|
||||
error_text.append("export STRIX_LLM='openai/gpt-5.4'\n", style="dim white")
|
||||
|
||||
if missing_optional_vars:
|
||||
for var in missing_optional_vars:
|
||||
|
||||
@@ -167,7 +167,7 @@ def get_global_report_state() -> Optional["ReportState"]:
|
||||
return _global_report_state
|
||||
|
||||
|
||||
def set_global_report_state(report_state: Optional["ReportState"]) -> None:
|
||||
def set_global_report_state(report_state: "ReportState") -> None:
|
||||
global _global_report_state # noqa: PLW0603
|
||||
_global_report_state = report_state
|
||||
# New run: drop any streamed-cost entries a prior run left unconsumed.
|
||||
|
||||
@@ -24,30 +24,3 @@ def _isolate_mcp_config(
|
||||
monkeypatch.setenv("STRIX_MCP_CONFIG", str(missing))
|
||||
monkeypatch.delenv("STRIX_MCP_ONLY", raising=False)
|
||||
monkeypatch.delenv("STRIX_MCP_EXCLUDE", raising=False)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _plain_terminal(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Make Rich output identical on every developer's machine.
|
||||
|
||||
Many CLI tests force ``isatty()`` to ``True`` to exercise the human-readable
|
||||
code path and then assert on the plain text. Rich picks its color system
|
||||
from ``TERM``, ``COLORTERM``, and ``FORCE_COLOR``, so on a real terminal
|
||||
those assertions would meet ANSI escape codes instead of the words they
|
||||
look for. A dumb terminal renders the same text without any styling.
|
||||
"""
|
||||
monkeypatch.setenv("TERM", "dumb")
|
||||
for name in ("COLORTERM", "FORCE_COLOR", "NO_COLOR", "TTY_COMPATIBLE"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_wallet_config(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Keep a developer's real mppx wallet out of the top-up tests.
|
||||
|
||||
``strix cloud billing topup`` chooses the Stripe Link flow or the
|
||||
preconfigured mppx wallet from these variables, so leaving them set would
|
||||
silently switch which branch a test runs.
|
||||
"""
|
||||
for name in ("MPPX_ACCOUNT", "MPPX_STRIPE_SECRET_KEY", "MPPX_STRIPE_PAYMENT_METHOD"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
@@ -6,7 +6,6 @@ import io
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.request
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
@@ -17,7 +16,7 @@ import requests
|
||||
from rich.console import Console
|
||||
|
||||
from strix.interface import cloud, platform_cli
|
||||
from strix.interface.cloud import http, render, runner, workspaces
|
||||
from strix.interface.cloud import billing, http, payment_proxy, render, runner, workspaces
|
||||
from strix.interface.cloud.spec import GROUP_HELP, SPEC
|
||||
|
||||
|
||||
@@ -148,7 +147,7 @@ def test_read_groups_have_safe_defaults(group: str, verb: str) -> None:
|
||||
resolved = runner.resolve(group, [])
|
||||
assert resolved is not None
|
||||
command, remaining = resolved
|
||||
assert command is SPEC[group][verb]
|
||||
assert command is runner.SPEC[group][verb]
|
||||
assert remaining == []
|
||||
|
||||
|
||||
@@ -562,7 +561,7 @@ def test_stored_token_is_never_sent_to_a_different_platform_origin(
|
||||
lambda: {"api_token": "stored-secret", "app_url": "https://app.strix.ai"},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
requests,
|
||||
http.requests,
|
||||
"request",
|
||||
lambda *_args, **_kwargs: pytest.fail("a mismatched origin must not receive the token"),
|
||||
)
|
||||
@@ -577,7 +576,7 @@ def test_stored_token_requires_an_issuer_binding(monkeypatch: pytest.MonkeyPatch
|
||||
monkeypatch.setattr(http, "_app_url_override", "https://app.strix.ai")
|
||||
monkeypatch.setattr(http, "read_record", lambda: {"api_token": "legacy-secret"})
|
||||
monkeypatch.setattr(
|
||||
requests,
|
||||
http.requests,
|
||||
"request",
|
||||
lambda *_args, **_kwargs: pytest.fail("an unbound token must not be sent"),
|
||||
)
|
||||
@@ -603,7 +602,7 @@ def test_stored_token_is_sent_only_to_its_bound_platform(
|
||||
seen.update(url=url, headers=kwargs["headers"])
|
||||
return FakeResponse(payload={"balance": 1})
|
||||
|
||||
monkeypatch.setattr(requests, "request", request)
|
||||
monkeypatch.setattr(http.requests, "request", request)
|
||||
response = http.request("GET", "/billing/credits")
|
||||
|
||||
assert response.status_code == 200
|
||||
@@ -627,7 +626,7 @@ def test_explicit_token_can_target_an_explicit_platform(
|
||||
seen.update(url=url, headers=kwargs["headers"])
|
||||
return FakeResponse(payload={"balance": 1})
|
||||
|
||||
monkeypatch.setattr(requests, "request", request)
|
||||
monkeypatch.setattr(http.requests, "request", request)
|
||||
override_value = "explicit-preview-" + str(1)
|
||||
response = http.request("GET", "/billing/credits", token=override_value)
|
||||
|
||||
@@ -707,9 +706,9 @@ def test_topup_noninteractive_requires_explicit_payment_approval(
|
||||
monkeypatch.setattr(
|
||||
http, "request", lambda *_a, **_k: FakeResponse(status_code=402, payload=challenge)
|
||||
)
|
||||
monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
|
||||
monkeypatch.setattr(runner.sys.stdin, "isatty", lambda: False)
|
||||
monkeypatch.setattr(
|
||||
subprocess,
|
||||
billing.subprocess,
|
||||
"run",
|
||||
lambda *_a, **_k: pytest.fail("wallet must not run without --yes"),
|
||||
)
|
||||
@@ -733,10 +732,10 @@ def test_topup_machine_output_never_prompts_even_with_terminal_stdin(
|
||||
monkeypatch.setattr(
|
||||
http, "request", lambda *_a, **_k: FakeResponse(status_code=402, payload=challenge)
|
||||
)
|
||||
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: stdout_tty)
|
||||
monkeypatch.setattr(runner.sys.stdin, "isatty", lambda: True)
|
||||
monkeypatch.setattr(runner.sys.stdout, "isatty", lambda: stdout_tty)
|
||||
monkeypatch.setattr(
|
||||
Console,
|
||||
runner.Console,
|
||||
"input",
|
||||
lambda *_a, **_k: pytest.fail("machine-readable top-up must not prompt"),
|
||||
)
|
||||
@@ -840,7 +839,7 @@ def test_topup_keeps_token_out_of_wallet_process_and_forwards_payment(
|
||||
upstream.update(method=method, url=url, **kwargs)
|
||||
return FakeResponse(payload=receipt, content=json.dumps(receipt).encode())
|
||||
|
||||
monkeypatch.setattr(requests, "request", fake_upstream_request)
|
||||
monkeypatch.setattr(payment_proxy.requests, "request", fake_upstream_request)
|
||||
|
||||
def fake_run(command: list[str], **kwargs: Any) -> Any:
|
||||
commands.append(command)
|
||||
@@ -906,7 +905,6 @@ def test_topup_wallet_failure_is_one_redacted_json_object(
|
||||
http, "request", lambda *_a, **_k: FakeResponse(status_code=402, payload=challenge)
|
||||
)
|
||||
monkeypatch.setattr(http, "api_token", lambda *_a, **_k: "tok")
|
||||
monkeypatch.setenv("MPPX_ACCOUNT", "agent")
|
||||
monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/npx")
|
||||
monkeypatch.setattr(
|
||||
subprocess,
|
||||
@@ -948,7 +946,6 @@ def test_topup_wallet_interruption_reports_unknown_payment_outcome(
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(http, "api_token", lambda *_a, **_k: "tok")
|
||||
monkeypatch.setenv("MPPX_ACCOUNT", "agent")
|
||||
monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/npx")
|
||||
monkeypatch.setattr(
|
||||
subprocess, "run", lambda *_a, **_k: (_ for _ in ()).throw(KeyboardInterrupt)
|
||||
@@ -974,7 +971,6 @@ def test_topup_non_json_wallet_success_requires_balance_verification(
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(http, "api_token", lambda *_a, **_k: "tok")
|
||||
monkeypatch.setenv("MPPX_ACCOUNT", "agent")
|
||||
monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/npx")
|
||||
monkeypatch.setattr(
|
||||
subprocess,
|
||||
@@ -1001,7 +997,6 @@ def test_topup_rejects_parseable_wallet_error_as_a_success(
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(http, "api_token", lambda *_a, **_k: "tok")
|
||||
monkeypatch.setenv("MPPX_ACCOUNT", "agent")
|
||||
monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/npx")
|
||||
monkeypatch.setattr(
|
||||
subprocess,
|
||||
@@ -1041,7 +1036,6 @@ def test_topup_does_not_trust_an_unobserved_wallet_receipt(
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(http, "api_token", lambda *_a, **_k: "tok")
|
||||
monkeypatch.setenv("MPPX_ACCOUNT", "agent")
|
||||
monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/npx")
|
||||
monkeypatch.setattr(
|
||||
subprocess,
|
||||
@@ -1062,7 +1056,7 @@ def test_topup_does_not_trust_an_unobserved_wallet_receipt(
|
||||
def test_topup_human_mode_requires_a_bridge_confirmed_receipt(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -1072,10 +1066,9 @@ def test_topup_human_mode_requires_a_bridge_confirmed_receipt(
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(http, "api_token", lambda *_a, **_k: "tok")
|
||||
monkeypatch.setenv("MPPX_ACCOUNT", "agent")
|
||||
monkeypatch.setattr(shutil, "which", lambda _name: "/usr/bin/npx")
|
||||
monkeypatch.setattr(
|
||||
requests,
|
||||
payment_proxy.requests,
|
||||
"request",
|
||||
lambda *_a, **_k: FakeResponse(status_code=200, content=b"<html>not a receipt</html>"),
|
||||
)
|
||||
@@ -1604,7 +1597,7 @@ def test_handoff_links_reject_non_http_schemes(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
capsys: Any,
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(runner.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -1889,7 +1882,7 @@ def test_workspace_use_preserves_definitive_conflict(
|
||||
def test_group_help_lists_all_verbs_instead_of_default_verb_help(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
assert cloud.run_cloud(["workspaces", "-h"]) == 0
|
||||
output = capsys.readouterr().out
|
||||
assert "workspaces verbs" in output
|
||||
@@ -1913,7 +1906,7 @@ def test_workspace_alias_routes_to_workspaces(monkeypatch: pytest.MonkeyPatch) -
|
||||
def test_workspace_human_list_is_numbered_and_hides_ids(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -1961,7 +1954,7 @@ def test_integrations_human_list_exposes_installation_id_and_json_stays_full(
|
||||
],
|
||||
"bitbucket_oauth_enabled": True,
|
||||
}
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(http, "request", lambda *_a, **_k: FakeResponse(payload=payload))
|
||||
|
||||
assert cloud.run_cloud(["integrations", "list"]) == 0
|
||||
@@ -1979,7 +1972,7 @@ def test_integrations_human_list_exposes_installation_id_and_json_stays_full(
|
||||
def test_pr_review_human_list_prioritizes_actionable_fields(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -2054,7 +2047,7 @@ def test_pr_review_human_list_shows_pull_request_state(
|
||||
capsys: Any,
|
||||
pr_state: str,
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -2117,7 +2110,7 @@ def test_scan_human_list_identifies_internal_and_uploaded_targets(
|
||||
record: dict[str, Any],
|
||||
expected_targets: tuple[str, ...],
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -2281,7 +2274,7 @@ def test_human_lists_prioritize_actionable_fields(
|
||||
visible: tuple[str, ...],
|
||||
hidden: tuple[str, ...],
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(http, "request", lambda *_a, **_k: FakeResponse(payload=payload))
|
||||
|
||||
assert cloud.run_cloud(command) == 0
|
||||
@@ -2295,7 +2288,7 @@ def test_human_lists_prioritize_actionable_fields(
|
||||
def test_token_human_list_shows_lifecycle_status(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -2652,7 +2645,7 @@ def test_nonstandard_human_list_envelopes_are_actionable(
|
||||
visible: tuple[str, ...],
|
||||
hidden: tuple[str, ...],
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(http, "request", lambda *_a, **_k: FakeResponse(payload=payload))
|
||||
|
||||
assert cloud.run_cloud(command) == 0
|
||||
@@ -2702,7 +2695,7 @@ def test_chat_credentials_human_view_separates_attached_and_available_sources(
|
||||
}
|
||||
],
|
||||
}
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(http, "request", lambda *_a, **_k: FakeResponse(payload=payload))
|
||||
|
||||
command = ["chat", "credentials", "chat-id", "--scan-ids", "source-scan-id"]
|
||||
@@ -2928,7 +2921,7 @@ def test_named_human_list_views_match_api_fields(
|
||||
visible: tuple[str, ...],
|
||||
hidden: tuple[str, ...],
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(http, "request", lambda *_a, **_k: FakeResponse(payload=payload))
|
||||
|
||||
assert cloud.run_cloud(command) == 0
|
||||
@@ -2942,7 +2935,7 @@ def test_named_human_list_views_match_api_fields(
|
||||
def test_supply_chain_org_summary_human_view_shows_totals_and_repository_risk(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -3103,7 +3096,7 @@ def test_wrapped_detail_human_views_are_unwrapped_and_actionable(
|
||||
visible: tuple[str, ...],
|
||||
hidden: tuple[str, ...],
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(http, "request", lambda *_a, **_k: FakeResponse(payload=payload))
|
||||
|
||||
assert cloud.run_cloud(command) == 0
|
||||
@@ -3117,7 +3110,7 @@ def test_wrapped_detail_human_views_are_unwrapped_and_actionable(
|
||||
def test_trace_human_view_summarizes_events_and_preserves_selector(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
seen_query: dict[str, Any] = {}
|
||||
|
||||
def fake_trace_request(_method: str, _path: str, **kwargs: Any) -> FakeResponse:
|
||||
@@ -3213,7 +3206,7 @@ def test_trace_human_view_summarizes_events_and_preserves_selector(
|
||||
def test_paginated_human_list_shows_total_and_continuation_command(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -3315,7 +3308,7 @@ def test_page_pagination_explains_an_out_of_range_page() -> None:
|
||||
def test_human_detail_preserves_long_prose_beyond_table_cell_limit(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
description = (
|
||||
" ".join(["authorization context"] * 12) + " final-description-marker\nsecond-line-marker"
|
||||
)
|
||||
@@ -3393,7 +3386,7 @@ def test_large_vulnerability_detail_prioritizes_evidence_and_remediation() -> No
|
||||
def test_test_user_human_view_joins_latest_verification(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -3490,7 +3483,7 @@ def test_wide_knowledge_table_keeps_title_readable_with_long_identifiers() -> No
|
||||
def test_human_get_prioritizes_details_and_hides_internal_identity_fields(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
|
||||
@@ -6,16 +6,13 @@ import argparse
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from rich.console import Console
|
||||
|
||||
from strix.interface import cloud, platform_cli
|
||||
from strix.interface.cloud import http, render, runner, source_scan
|
||||
from strix.interface.cloud.source_upload import prepare_source
|
||||
from strix.interface.main import main as interface_main
|
||||
|
||||
|
||||
@@ -172,7 +169,7 @@ def test_connector_enrollment_command_is_complete_multiline_and_terminal_safe(
|
||||
" -e LABEL=before\x1b]52;c;copied\x07after \\\n"
|
||||
" ghcr.io/usestrix/connector:latest"
|
||||
)
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -296,8 +293,8 @@ def test_source_prompt_shows_paths_and_literal_confirmation(
|
||||
return "n"
|
||||
|
||||
monkeypatch.setattr(console, "input", answer)
|
||||
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(source_scan.sys.stdin, "isatty", lambda: True)
|
||||
monkeypatch.setattr(source_scan.sys.stdout, "isatty", lambda: True)
|
||||
args = argparse.Namespace(
|
||||
source=str(tmp_path),
|
||||
dry_run=False,
|
||||
@@ -327,7 +324,7 @@ def test_source_prompt_interruption_removes_temporary_archive(
|
||||
(tmp_path / "app.py").write_text("print('ok')\n", encoding="utf-8")
|
||||
console = Console(file=io.StringIO(), width=100)
|
||||
archive_paths: list[Path] = []
|
||||
original_prepare = prepare_source
|
||||
original_prepare = source_scan.prepare_source
|
||||
|
||||
def capture_bundle(*args: Any, **kwargs: Any) -> Any:
|
||||
bundle = original_prepare(*args, **kwargs)
|
||||
@@ -339,8 +336,8 @@ def test_source_prompt_interruption_removes_temporary_archive(
|
||||
|
||||
monkeypatch.setattr(source_scan, "prepare_source", capture_bundle)
|
||||
monkeypatch.setattr(console, "input", interrupt)
|
||||
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(source_scan.sys.stdin, "isatty", lambda: True)
|
||||
monkeypatch.setattr(source_scan.sys.stdout, "isatty", lambda: True)
|
||||
args = argparse.Namespace(
|
||||
source=str(tmp_path),
|
||||
dry_run=False,
|
||||
@@ -397,7 +394,7 @@ def test_device_login_rejects_non_http_verification_url(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(
|
||||
requests,
|
||||
platform_cli.requests,
|
||||
"post",
|
||||
lambda *_a, **_k: FakeResponse(
|
||||
{
|
||||
@@ -430,7 +427,7 @@ def test_boolean_query_values_are_lowercase_for_url_search_params(
|
||||
seen["params"] = kwargs.get("params")
|
||||
return FakeResponse({"items": []})
|
||||
|
||||
monkeypatch.setattr(requests, "request", fake_request)
|
||||
monkeypatch.setattr(http.requests, "request", fake_request)
|
||||
http.request("GET", "/test", query={"enabled": True, "disabled": False})
|
||||
assert seen["params"] == {"enabled": "true", "disabled": "false"}
|
||||
|
||||
@@ -484,7 +481,7 @@ def test_binary_response_refuses_to_write_to_a_terminal(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
capsys: Any,
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(runner.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -516,7 +513,7 @@ def test_binary_response_can_be_intentionally_redirected(
|
||||
return None
|
||||
|
||||
redirected = RedirectedStdout()
|
||||
monkeypatch.setattr(sys, "stdout", redirected)
|
||||
monkeypatch.setattr(runner.sys, "stdout", redirected)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
@@ -537,7 +534,7 @@ def test_redirected_binary_errors_never_append_diagnostics_to_stdout(
|
||||
def iter_content(self, *, chunk_size: int) -> Any:
|
||||
assert chunk_size == 1024 * 1024
|
||||
yield b"%PDF-partial"
|
||||
raise requests.ConnectionError("connection lost")
|
||||
raise http.requests.ConnectionError("connection lost")
|
||||
|
||||
response = (
|
||||
FakeResponse({"detail": "report rejected"}, status_code=500)
|
||||
@@ -648,7 +645,7 @@ def test_binary_download_streams_and_preserves_existing_file_on_failure(
|
||||
def iter_content(self, *, chunk_size: int) -> Any:
|
||||
assert chunk_size == 1024 * 1024
|
||||
yield b"partial"
|
||||
raise requests.ConnectionError("connection lost")
|
||||
raise http.requests.ConnectionError("connection lost")
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
@@ -773,7 +770,7 @@ def test_session_help_is_specific_and_human_whoami_shows_scopes(
|
||||
"scopes": ["scans:read", "organizations:read"],
|
||||
}
|
||||
)
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(platform_cli.sys.stdout, "isatty", lambda: True)
|
||||
assert cloud.run_cloud(["whoami", "--help"]) == 0
|
||||
who_help = capsys.readouterr().out
|
||||
assert "strix cloud whoami" in who_help
|
||||
@@ -787,7 +784,7 @@ def test_non_tty_whoami_and_logout_emit_json(
|
||||
) -> None:
|
||||
monkeypatch.delenv("STRIX_API_TOKEN", raising=False)
|
||||
monkeypatch.setattr(platform_cli, "AUTH_PATH", tmp_path / "auth.json")
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: False)
|
||||
monkeypatch.setattr(platform_cli.sys.stdout, "isatty", lambda: False)
|
||||
platform_cli.save_record(
|
||||
{
|
||||
"api_token": "secret",
|
||||
@@ -802,7 +799,7 @@ def test_non_tty_whoami_and_logout_emit_json(
|
||||
assert json.loads(capsys.readouterr().out)["email"] == "agent@example.test"
|
||||
|
||||
monkeypatch.setattr(
|
||||
requests,
|
||||
platform_cli.requests,
|
||||
"delete",
|
||||
lambda *_args, **_kwargs: type("Response", (), {"status_code": 200})(),
|
||||
)
|
||||
@@ -834,7 +831,7 @@ def test_scope_picker_labels_match_the_server_presets() -> None:
|
||||
def test_noninteractive_login_never_prompts_for_workspace(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
|
||||
monkeypatch.setattr(platform_cli.sys.stdin, "isatty", lambda: False)
|
||||
console = Console(file=io.StringIO())
|
||||
console.input = lambda *_args, **_kwargs: pytest.fail("must not prompt") # type: ignore[method-assign]
|
||||
|
||||
@@ -899,10 +896,10 @@ def test_device_flow_slow_down_never_exceeds_the_poll_interval_cap(
|
||||
sleeps.append(seconds)
|
||||
now += seconds
|
||||
|
||||
monkeypatch.setattr(requests, "post", post)
|
||||
monkeypatch.setattr(platform_cli.requests, "post", post)
|
||||
monkeypatch.setattr(platform_cli, "_app_url", lambda: "https://example.test")
|
||||
monkeypatch.setattr(time, "monotonic", monotonic)
|
||||
monkeypatch.setattr(time, "sleep", sleep)
|
||||
monkeypatch.setattr(platform_cli.time, "monotonic", monotonic)
|
||||
monkeypatch.setattr(platform_cli.time, "sleep", sleep)
|
||||
|
||||
with pytest.raises(platform_cli.PlatformAuthError, match="expired"):
|
||||
platform_cli._run_device_flow(
|
||||
@@ -936,9 +933,9 @@ def test_device_flow_accepts_external_authkit_url_and_binds_token_origin(
|
||||
),
|
||||
]
|
||||
)
|
||||
monkeypatch.setattr(requests, "post", lambda *_a, **_k: next(responses))
|
||||
monkeypatch.setattr(platform_cli.requests, "post", lambda *_a, **_k: next(responses))
|
||||
monkeypatch.setattr(platform_cli, "_app_url", lambda: "https://preview.strix.ai")
|
||||
monkeypatch.setattr(time, "sleep", lambda _seconds: None)
|
||||
monkeypatch.setattr(platform_cli.time, "sleep", lambda _seconds: None)
|
||||
|
||||
record = platform_cli._run_device_flow(
|
||||
Console(file=io.StringIO()),
|
||||
@@ -987,7 +984,7 @@ def test_root_help_accepts_json_before_help_and_leaf_help_stays_specific(
|
||||
def test_non_tty_dispatcher_always_emits_structured_json(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: False)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: False)
|
||||
|
||||
assert cloud.run_cloud([]) == 0
|
||||
assert json.loads(capsys.readouterr().out)["command"] == "strix cloud"
|
||||
@@ -1023,7 +1020,7 @@ def test_source_upload_rejects_untrusted_destinations_before_reading_file(
|
||||
source.write_bytes(b"approved source")
|
||||
monkeypatch.setattr(http, "_app_url_override", "https://app.strix.ai")
|
||||
monkeypatch.setattr(
|
||||
requests,
|
||||
http.requests,
|
||||
"put",
|
||||
lambda *_args, **_kwargs: pytest.fail("an untrusted URL must not receive source bytes"),
|
||||
)
|
||||
@@ -1062,7 +1059,7 @@ def test_source_upload_allows_only_managed_or_same_origin_storage(
|
||||
return response
|
||||
|
||||
monkeypatch.setattr(http, "_app_url_override", app_url)
|
||||
monkeypatch.setattr(requests, "put", put)
|
||||
monkeypatch.setattr(http.requests, "put", put)
|
||||
http.upload_file(signed_url, "upload-token", source)
|
||||
|
||||
assert request_options["allow_redirects"] is False
|
||||
@@ -1083,7 +1080,7 @@ def test_source_upload_refuses_redirects_without_following_them(
|
||||
return response
|
||||
|
||||
monkeypatch.setattr(http, "_app_url_override", "https://app.strix.ai")
|
||||
monkeypatch.setattr(requests, "put", put)
|
||||
monkeypatch.setattr(http.requests, "put", put)
|
||||
|
||||
with pytest.raises(http.CloudError, match="unexpected redirect"):
|
||||
http.upload_file(
|
||||
@@ -1098,7 +1095,7 @@ def test_source_upload_refuses_redirects_without_following_them(
|
||||
def test_one_time_api_token_has_save_now_warning(
|
||||
monkeypatch: pytest.MonkeyPatch, capsys: Any
|
||||
) -> None:
|
||||
monkeypatch.setattr(sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(render.sys.stdout, "isatty", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
http,
|
||||
"request",
|
||||
|
||||
@@ -3,11 +3,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from strix.interface import cloud
|
||||
from strix.interface.cloud import http, runner
|
||||
@@ -32,7 +30,7 @@ class FakeResponse:
|
||||
@pytest.fixture(autouse=True)
|
||||
def _token(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("STRIX_API_TOKEN", "idempotency-test-token")
|
||||
monkeypatch.setattr(time, "sleep", lambda _seconds: None)
|
||||
monkeypatch.setattr(runner.time, "sleep", lambda _seconds: None)
|
||||
|
||||
|
||||
def test_scan_start_generates_and_sends_one_stable_key(
|
||||
@@ -199,7 +197,7 @@ def test_http_client_places_key_in_the_header(monkeypatch: pytest.MonkeyPatch) -
|
||||
seen.update(kwargs)
|
||||
return FakeResponse({"ok": True})
|
||||
|
||||
monkeypatch.setattr(requests, "request", request)
|
||||
monkeypatch.setattr(http.requests, "request", request)
|
||||
http.request("POST", "/scans", body={}, idempotency_key="header-key")
|
||||
assert seen["headers"]["Idempotency-Key"] == "header-key"
|
||||
assert seen["headers"]["Authorization"] == "Bearer idempotency-test-token"
|
||||
|
||||
@@ -7,7 +7,6 @@ import urllib.request
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from strix.interface.cloud import payment_proxy
|
||||
|
||||
@@ -40,8 +39,7 @@ def _post(url: str, body: bytes, headers: dict[str, str] | None = None) -> bytes
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=2) as response: # noqa: S310
|
||||
body_bytes: bytes = response.read()
|
||||
return body_bytes
|
||||
return response.read()
|
||||
|
||||
|
||||
def test_bridge_bounds_decompressed_upstream_response(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@@ -52,7 +50,7 @@ def test_bridge_bounds_decompressed_upstream_response(monkeypatch: pytest.Monkey
|
||||
return response
|
||||
|
||||
monkeypatch.setattr(payment_proxy, "_MAX_UPSTREAM_RESPONSE_BYTES", 4)
|
||||
monkeypatch.setattr(requests, "request", fake_request)
|
||||
monkeypatch.setattr(payment_proxy.requests, "request", fake_request)
|
||||
|
||||
with payment_proxy.wallet_payment_bridge(
|
||||
upstream_url="https://app.example.test/api/v1/billing/topup",
|
||||
@@ -82,7 +80,7 @@ def test_bridge_forwards_only_the_approved_request_and_protected_headers(
|
||||
captured.append(kwargs)
|
||||
return _StreamingResponse([b'{"ok":true}'])
|
||||
|
||||
monkeypatch.setattr(requests, "request", fake_request)
|
||||
monkeypatch.setattr(payment_proxy.requests, "request", fake_request)
|
||||
with payment_proxy.wallet_payment_bridge(
|
||||
upstream_url="https://app.example.test/api/v1/billing/topup",
|
||||
api_token="strix-secret", # noqa: S106
|
||||
@@ -126,7 +124,7 @@ def test_bridge_limits_valid_wallet_attempts(monkeypatch: pytest.MonkeyPatch) ->
|
||||
calls += 1
|
||||
return _StreamingResponse([b"{}"])
|
||||
|
||||
monkeypatch.setattr(requests, "request", fake_request)
|
||||
monkeypatch.setattr(payment_proxy.requests, "request", fake_request)
|
||||
with payment_proxy.wallet_payment_bridge(
|
||||
upstream_url="https://app.example.test/api/v1/billing/topup",
|
||||
api_token="strix-secret", # noqa: S106
|
||||
|
||||
@@ -6,7 +6,6 @@ import json
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from rich.console import Console
|
||||
|
||||
from strix.interface import cloud, platform_cli, platform_identity
|
||||
@@ -56,7 +55,7 @@ def test_http_workspace_pin_is_captured_once(
|
||||
sent.append(dict(kwargs["headers"]))
|
||||
return Response({})
|
||||
|
||||
monkeypatch.setattr(requests, "request", fake_request)
|
||||
monkeypatch.setattr(http.requests, "request", fake_request)
|
||||
http.configure()
|
||||
platform_cli.save_record(
|
||||
{
|
||||
@@ -117,7 +116,7 @@ def test_logout_keeps_local_token_when_remote_outcome_is_not_definitive(
|
||||
}
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
requests,
|
||||
platform_cli.requests,
|
||||
"delete",
|
||||
lambda *_args, **_kwargs: Response({"detail": "unavailable"}, 503),
|
||||
)
|
||||
|
||||
@@ -208,191 +208,6 @@ 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"
|
||||
|
||||
@@ -114,14 +114,7 @@ def test_config_file_loads_dedupe_model(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
for key in (
|
||||
"STRIX_LLM",
|
||||
"LLM_API_KEY",
|
||||
"OPENAI_API_KEY",
|
||||
"LLM_API_BASE",
|
||||
"STRIX_DEDUPE_MODEL",
|
||||
"STRIX_DEDUPE_REASONING_EFFORT",
|
||||
):
|
||||
for key in ("STRIX_LLM", "STRIX_DEDUPE_MODEL", "STRIX_DEDUPE_REASONING_EFFORT"):
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text(
|
||||
|
||||
@@ -12,7 +12,6 @@ would let it escape and surface a traceback on every teardown.
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
@@ -23,10 +22,6 @@ from requests.exceptions import ConnectionError as RequestsConnectionError
|
||||
from strix.runtime.docker_client import StrixDockerSandboxClient
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from agents.sandbox.session.sandbox_session import SandboxSession
|
||||
|
||||
|
||||
def _client_with_kill_error(exc: Exception) -> StrixDockerSandboxClient:
|
||||
"""A StrixDockerSandboxClient whose containers.get(...).kill() raises ``exc``."""
|
||||
client = StrixDockerSandboxClient.__new__(StrixDockerSandboxClient)
|
||||
@@ -36,10 +31,9 @@ def _client_with_kill_error(exc: Exception) -> StrixDockerSandboxClient:
|
||||
return client
|
||||
|
||||
|
||||
def _session(container_id: str | None = "abc123") -> SandboxSession:
|
||||
def _session() -> object:
|
||||
# delete() reads session._inner.state.container_id
|
||||
fake = SimpleNamespace(_inner=SimpleNamespace(state=SimpleNamespace(container_id=container_id)))
|
||||
return cast("SandboxSession", fake)
|
||||
return SimpleNamespace(_inner=SimpleNamespace(state=SimpleNamespace(container_id="abc123")))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -51,7 +45,7 @@ def _session(container_id: str | None = "abc123") -> SandboxSession:
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_swallows_best_effort_kill_errors(exc: Exception) -> None:
|
||||
async def test_delete_swallows_best_effort_kill_errors(exc):
|
||||
"""A torn-down socket (ConnectionError) or a gone/unhappy container
|
||||
(NotFound/APIError) during the kill must not propagate; delete() still
|
||||
delegates to the SDK's delete()."""
|
||||
@@ -68,7 +62,7 @@ async def test_delete_swallows_best_effort_kill_errors(exc: Exception) -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_does_not_swallow_unrelated_errors() -> None:
|
||||
async def test_delete_does_not_swallow_unrelated_errors():
|
||||
"""A programming error (e.g. ValueError) is not part of best-effort kill and
|
||||
must still propagate."""
|
||||
client = _client_with_kill_error(ValueError("boom"))
|
||||
@@ -77,11 +71,11 @@ async def test_delete_does_not_swallow_unrelated_errors() -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_noop_without_container_id() -> None:
|
||||
async def test_delete_noop_without_container_id():
|
||||
"""No container_id -> no kill attempt, just delegate."""
|
||||
client = StrixDockerSandboxClient.__new__(StrixDockerSandboxClient)
|
||||
client.docker_client = MagicMock()
|
||||
session = _session(container_id=None)
|
||||
session = SimpleNamespace(_inner=SimpleNamespace(state=SimpleNamespace(container_id=None)))
|
||||
|
||||
with patch.object(
|
||||
DockerSandboxClient, "delete", new=AsyncMock(return_value=session)
|
||||
|
||||
@@ -72,13 +72,6 @@ def test_recommended_models_are_matched_case_insensitively() -> None:
|
||||
"moonshot/kimi-k2.6",
|
||||
"kimi-k2.7-code",
|
||||
"moonshot/kimi-k3",
|
||||
"anthropic/claude-fable-5-1",
|
||||
"vertex_ai/claude-fable-5-1@default",
|
||||
"gemini/gemini-3.7-flash",
|
||||
"glm-5.3",
|
||||
"zai/glm-5.3-flash",
|
||||
"openrouter/z-ai/glm-5.3",
|
||||
"novita/zai-org/glm-5.2",
|
||||
],
|
||||
)
|
||||
def test_frontier_model_families_are_accepted(model_name: str) -> None:
|
||||
@@ -99,9 +92,6 @@ def test_frontier_model_families_are_accepted(model_name: str) -> None:
|
||||
"openrouter/x-ai/grok-4",
|
||||
"mistral/mistral-medium-3-5",
|
||||
"mistral/magistral-medium-latest",
|
||||
"zai/glm-4.7",
|
||||
"openrouter/z-ai/glm-5",
|
||||
"custom-provider/glm-5.3-local",
|
||||
],
|
||||
)
|
||||
def test_non_frontier_models_are_rejected(model_name: str) -> None:
|
||||
|
||||
@@ -11,8 +11,7 @@ PYPROJECT = Path(__file__).resolve().parent.parent / "pyproject.toml"
|
||||
|
||||
def _optional_dependencies() -> dict[str, list[str]]:
|
||||
data = tomllib.loads(PYPROJECT.read_text(encoding="utf-8"))
|
||||
extras: dict[str, list[str]] = data["project"]["optional-dependencies"]
|
||||
return extras
|
||||
return data["project"]["optional-dependencies"]
|
||||
|
||||
|
||||
def test_vertex_extra_pins_google_auth() -> None:
|
||||
|
||||
@@ -185,4 +185,6 @@ async def test_roster_is_persisted_even_without_a_status_sink(
|
||||
)
|
||||
|
||||
assert persisted, "roster must persist even when no status sink is attached"
|
||||
assert persisted[-1] == [{"name": "local_fs", "provider": None, "tool_count": 3, "dead": False}]
|
||||
assert persisted[-1] == [
|
||||
{"name": "local_fs", "provider": None, "tool_count": 3, "dead": False}
|
||||
]
|
||||
|
||||
@@ -34,8 +34,7 @@ def _finding(**overrides: Any) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _rule_tags(doc: dict[str, Any]) -> list[str]:
|
||||
tags: list[str] = doc["runs"][0]["tool"]["driver"]["rules"][0]["properties"]["tags"]
|
||||
return tags
|
||||
return doc["runs"][0]["tool"]["driver"]["rules"][0]["properties"]["tags"]
|
||||
|
||||
|
||||
def test_stride_tags_on_rule_for_known_cwe() -> None:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
@@ -10,40 +9,13 @@ import pytest
|
||||
from strix.core.sessions import open_agent_session
|
||||
|
||||
|
||||
def _fd_dir() -> Path | None:
|
||||
def _count_open_fds() -> int | None:
|
||||
for path in (Path("/proc/self/fd"), Path("/dev/fd")):
|
||||
if path.is_dir():
|
||||
return path
|
||||
return len(list(path.iterdir()))
|
||||
return None
|
||||
|
||||
|
||||
def _count_open_fds() -> int | None:
|
||||
fd_dir = _fd_dir()
|
||||
return None if fd_dir is None else len(list(fd_dir.iterdir()))
|
||||
|
||||
|
||||
def _count_open_fds_to(files: list[Path]) -> int | None:
|
||||
"""Count the descriptors this process holds on exactly ``files``.
|
||||
|
||||
Matching on inode rather than on the process-wide total keeps the check
|
||||
immune to sockets and pipes that unrelated background threads open while
|
||||
the test runs.
|
||||
"""
|
||||
fd_dir = _fd_dir()
|
||||
if fd_dir is None:
|
||||
return None
|
||||
wanted = {(stat.st_dev, stat.st_ino) for stat in (path.stat() for path in files)}
|
||||
held = 0
|
||||
for entry in fd_dir.iterdir():
|
||||
try:
|
||||
stat = os.fstat(int(entry.name))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if (stat.st_dev, stat.st_ino) in wanted:
|
||||
held += 1
|
||||
return held
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sessions_hold_no_descriptors_while_parked(tmp_path: Path) -> None:
|
||||
"""Descriptor use must track live operations, not the number of sessions.
|
||||
@@ -53,20 +25,21 @@ async def test_sessions_hold_no_descriptors_while_parked(tmp_path: Path) -> None
|
||||
scan, and fan-out multiplies those handles until the process runs out of file
|
||||
descriptors (#1018). A session that is not mid-operation should hold none.
|
||||
"""
|
||||
if _fd_dir() is None:
|
||||
baseline = _count_open_fds()
|
||||
if baseline is None:
|
||||
pytest.skip("no /proc/self/fd or /dev/fd on this platform")
|
||||
|
||||
db_paths = [tmp_path / f"s{i}.db" for i in range(60)]
|
||||
sessions = [open_agent_session(f"a{i}", path) for i, path in enumerate(db_paths)]
|
||||
sessions = [open_agent_session(f"a{i}", tmp_path / f"s{i}.db") for i in range(60)]
|
||||
try:
|
||||
for _ in range(4):
|
||||
await asyncio.gather(
|
||||
*(s.add_items([{"role": "user", "content": "x"}]) for s in sessions)
|
||||
)
|
||||
await asyncio.gather(*(s.get_items() for s in sessions))
|
||||
parked = _count_open_fds_to(db_paths)
|
||||
# 60 parked sessions, yet none of them holds its database open.
|
||||
assert parked == 0, f"parked sessions hold {parked} database descriptors"
|
||||
parked = _count_open_fds()
|
||||
assert parked is not None
|
||||
# 60 parked sessions, yet descriptors are back at the baseline.
|
||||
assert parked - baseline <= 5, f"parked fds grew by {parked - baseline}"
|
||||
finally:
|
||||
for s in sessions:
|
||||
s.close()
|
||||
|
||||
Reference in New Issue
Block a user