Metadata-Version: 2.4
Name: zeroday-cli
Version: 0.1.1
Summary: zeroday: an interactive AI agent CLI with MCP and Agent Skills support
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: src/zeroday/vendor/claude_cybersecurity_skill/LICENSE
License-File: src/zeroday/vendor/claude_cybersecurity_skill/NOTICE
Requires-Dist: httpx>=0.27
Requires-Dist: PyYAML>=6.0
Requires-Dist: reportlab>=4.0
Requires-Dist: requests>=2.32
Requires-Dist: keyring>=25.0
Requires-Dist: paramiko>=3.4
Requires-Dist: packaging>=23.2
Provides-Extra: browser
Requires-Dist: playwright>=1.48; extra == "browser"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

# zeroday

An interactive AI agent CLI in Python for coding, defensive security research, automation, and general assistance. It supports OpenRouter and local OpenAI-compatible models, project/user Agent Skills, and opt-in MCP stdio tools. MCP server startup and every tool call require interactive approval.

Python 3.10+ is required. Runtime dependencies are declared in `pyproject.toml` and installed with the package.

## Project structure

```
zeroday/
├── pyproject.toml              # package metadata, `zeroday` console script
├── README.md
├── .gitignore
├── src/zeroday/
│   ├── __init__.py             # version
│   ├── __main__.py             # `python -m zeroday`
│   ├── cli.py                  # commands + interactive agent chat
│   ├── ui.py                   # console UI + UI abstraction for the chat loop
│   ├── tui/                    # opencode-style full-screen terminal interface
│   │   ├── app.py              # layout, transcript, input, approvals, streaming
│   │   ├── terminal.py         # raw mode, alt screen, key decoding
│   │   ├── markdown.py         # markdown rendering for replies
│   │   └── theme.py            # colors and styles
│   ├── agent_tools.py          # approval-gated project and browser tools
│   ├── browser.py              # visible Playwright browser session + page cloning
│   ├── config.py               # config file, env file, dotted `config set`
│   ├── session.py              # conversation history + save/load
│   ├── skills.py               # project/user SKILL.md loader
│   ├── mcp.py                  # MCP stdio client and approval gate
│   └── providers/
│       ├── __init__.py         # build_provider(): config -> provider (+ API-key check)
│       ├── base.py             # Provider interface, ProviderError
│       └── openai_compat.py    # streaming/non-streaming client (urllib, SSE parser)
└── tests/                      # mock API/MCP servers and offline tests
```

## Install: Debian / Ubuntu

```bash
sudo apt update
sudo apt install -y python3 python3-venv python3-pip git

cd zeroday
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"        # drop [dev] if you do not want pytest

zeroday --version
```

Install globally for your user instead of a venv: `sudo apt install -y pipx && pipx install .`

## Install: Windows (PowerShell)

```powershell
winget install -e --id Python.Python.3.12     # skip if Python 3.10+ is installed; reopen PowerShell after

cd zeroday
py -m venv .venv
.venv\Scripts\Activate.ps1                    # if blocked: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
pip install -e ".[dev]"

zeroday --version
```

## Sign in

Sign in to the configured ZeroDay website account before using CLI commands:

```bash
zeroday auth login
zeroday auth status
```

`zeroday auth login` opens the website authorization flow and remembers the verified login in the operating system credential store for one hour. Only users with an active paid website subscription can authorize or use the CLI. Normal CLI commands require a verified login and retrieve the current OpenRouter key pool from the website database table `api` (`api_type = 2`); all matching keys are used in database order. No provider key is stored in the CLI `.env` file. If a command itself opens the login flow, that login authorizes only that invocation; use `zeroday auth login` explicitly to avoid being asked again on subsequent commands. After an explicit login expires, the next command opens the login flow. `zeroday auth login`, `zeroday auth status`, `zeroday auth logout`, `--help`, and `--version` remain available without an active login.

After login, the CLI checks PyPI at most once per day and offers a newer release with an explicit yes/no prompt. It never installs an update without consent. Press Enter to continue and update later; use `zeroday --check-updates` to check immediately or `zeroday --upgrade` to explicitly install the latest release with the current Python interpreter's `pip`. The update cache lives in the user's ZeroDay configuration directory. Network failures do not interrupt CLI use.

## Set up a provider

### OpenRouter API (default provider: `openrouter`)

OpenRouter keys for the website CLI are managed in the website database. Add every key to the `api` table with `api_type = 2`; the CLI loads the complete pool on each normal command and rotates through keys after HTTP 401 or 429.

If you already have a config file from an earlier version, update its saved model with:

```bash
zeroday config set providers.openrouter.model openrouter/free
```

For a different OpenAI-compatible provider, configure a key pool in environment variables:

```powershell
zeroday config set providers.groq.api_key_envs '["GROQ_API_KEY", "GROQ_API_KEY_2"]'
```

```dotenv
GROQ_API_KEY=first-key
GROQ_API_KEY_2=second-key
```

The provider tries the next configured key after HTTP 401 or 429 and keeps using a key that succeeds. The legacy `api_key_env` setting still works when `api_key_envs` is not configured. The website `openrouter` provider uses its database key pool instead.

Once the key is set, the default provider is ready:

```bash
zeroday ask "Say hello"
zeroday models llama
```

The default model is `openrouter/free`, which routes chat requests to an available free model. Free model availability and limits are determined by OpenRouter.

`recraft/recraft-v4.1-flash-v2:free` is an image-generation model served through OpenRouter's Images API, not the chat-completions API used by this CLI. It cannot be selected with `-m` in the current text-chat CLI. See [OpenRouter's Recraft API page](https://openrouter.ai/recraft/recraft-v4.1-flash-v2:free) for its API and pricing details.

### Local models (optional)

Ollama example:

```bash
# Debian
curl -fsSL https://ollama.com/install.sh | sh
# Windows (PowerShell)
winget install Ollama.Ollama

ollama pull llama3.2
zeroday ask -p local "Say hello"
```

Other servers: point `local` at them.

```bash
zeroday config set providers.local.base_url http://localhost:1234/v1   # LM Studio
zeroday config set providers.local.base_url http://localhost:8080/v1   # llama-server
zeroday config set providers.local.model your-model-name
```

## Usage

```bash
zeroday                                  # interactive agent chat (full-screen TUI)
zeroday chat --ui plain                  # plain line-based REPL
zeroday chat --no-agent                  # chat without local tools
zeroday chat --skill code-review         # activate a project skill
zeroday chat --mcp                       # connect configured MCP servers
zeroday ask "What is a mutex?"
cat error.log | zeroday ask "Why did this fail?"
zeroday ask --no-stream -t 0.2 "Give me a regex for ISO dates"
zeroday providers                        # shows providers and whether keys are set
zeroday models [filter]
zeroday doctor                           # check local prerequisites and integrations
zeroday doctor --json                    # emit the same checks as JSON
zeroday skills                           # list discovered skills
zeroday mcp list                         # list configured MCP servers
zeroday config show | path | init | set <key> <value>
```

Per-run flags: `-p provider`, `-m model`, `--base-url URL`, `-s "system prompt"`, `-t temperature`, `--max-tokens N`, `--no-stream`, `--ui auto|tui|plain`.
Environment overrides: `ZERODAY_PROVIDER`, `ZERODAY_MODEL`, `ZERODAY_HOME` (config directory).

In a terminal `zeroday chat` starts an opencode-style full-screen interface (header, sidebar, scrollable transcript, bordered prompt, streamed replies, tool-call blocks, and approval dialogs). Use `--ui plain` for the classic line-based REPL.

`zeroday doctor` reports dependency, scope, database, tool-registry, browser, scanner, provider, and skill-engine health. It reports registered, implemented, configured, available, and tested states separately. The provider check uses configured authentication to make a bounded read-only request to the default provider's models endpoint and verifies the configured model. The Burp check makes an authenticated, read-only request to its loopback API description endpoint; SQLMap detection does not execute or download anything. The command does not scan configured targets, install packages, or modify scope. Use `--json` for machine-readable output; credential values are never included.

Requests use a conservative context budget. If a prompt exceeds it, the CLI removes older complete chat turns first, then transparently trims oversized message text while retaining its beginning and end. A notice reports when compaction occurred; the saved in-memory conversation is left intact. OpenRouter context-length errors trigger one smaller retry when the provider supplies its context limit.

In chat: `/help /exit /clear /retry /system /model /provider /models /agent /actions /skills /skill /mcp /clone /offline /save /load`. `/clone <url> [path]` and `/offline <url> [path]` open a page in the controlled browser and write a local single-file HTML copy (default: `clones/<page>.html`). Agent requests show progress while waiting for the model. `/actions` shows the current chat's approval and tool activity log.

## Pentester engine

The pentesting engine (`src/zeroday/pentester/`) exposes compatible pentesting tools to the CLI and AI agent. All execution passes through the `PentestingEngine` and is gated by scope, permissions, and the audit logger.

CLI commands (require a verified login first):

```bash
zeroday pentest tools          # list tools + states
zeroday pentest categories     # category distribution
zeroday pentest search <kw>    # search tools by keyword
zeroday pentest info <tool>    # tool metadata + dependency status
zeroday pentest check          # dependency check for every tool
zeroday pentest status         # tool count + recent results
zeroday pentest config         # engine config
zeroday pentest enable <tool>  # enable a tool
zeroday pentest disable <tool> # disable a tool
zeroday pentest results        # recent results
zeroday pentest report         # report (tools run + findings)
zeroday pentest docker status|rebuild
```

Agent tools: `pentest_list_tools`, `pentest_tool_info`, `pentest_run` (all route through `PentestingEngine`).

Execution rules:
- Every `run_tool()` path carries an honest `scope_validated` flag.
- Scope validation happens before tool execution. A blocked target returns `status: "blocked"` with `scope_validated: False`.
- Missing dependencies return `status: "error"` with `scope_validated: True` (when the target itself passes scope).
- Audit logging records every pentest run.
- The MCP adapter never executes arbitrary MCP commands directly; every call goes through `PentestingEngine.run_tool`.

Test results:
- `src/zeroday/pentester/tests/`: 23 passed
- Full suite `python -m pytest`: 251 passed, 6 skipped, 4 failed (all 4 in `tests/test_research_engine.py`, a separate research engine subsystem, unaffected by the pentester).

## Agent Skills

Create a project skill at `.zeroday/skills/<skill-name>/SKILL.md` or a user skill at `<config dir>/skills/<skill-name>/SKILL.md`:

```markdown
---
name: code-review
description: Review project changes for correctness and maintainability.
---

Inspect the relevant code and tests. Explain findings with file paths.
Do not modify files unless the user asks.
```

List every discovered skill with `zeroday skills`. Check counts with `zeroday skills --stats`, or preview relevance with `zeroday skills --search "scan https://example.com for vulnerabilities"`. In chat, `/skills` lists loaded skills, and `/actions` shows automatic selections. At most three relevant skills are added to each request to keep unrelated material out of the model context; skills are not all pasted into every prompt. Activate one explicitly with `zeroday chat --skill code-review` or `/skill code-review`; `/skill off` deactivates it. User and project skills override bundled skills with the same name. Skills are instructions, not executable plugins.

The CLI bundles all 22 skill guides and their 34 Python helper scripts from [Riyan Pratama (Masriyan / sudo3rs)'s Claude-Code-CyberSecurity-Skill collection](https://github.com/Masriyan/Claude-Code-CyberSecurity-Skill), pinned at commit `3aa77d84fb64cf07b550f6be4544bb91292db89f`. The guides can be auto-selected or explicitly activated. They are supplementary instructions: the existing system prompt, configured scope, registered tools, and approvals take precedence. Helper scripts are included as reference assets but are not automatically executable by the agent; this CLI does not expose a general shell tool. The upstream `LICENSE` and `NOTICE` are included in the vendored directory; see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for attribution and integration notes.

## Local file, GitHub, browser, and website posture tools

Interactive chat enables local tools by default; pass `--no-agent` to disable them. File paths are restricted to the directory where the CLI was started; absolute paths, parent traversal, and symlinks are rejected. The CLI asks before each directory listing and file read. Credential files (including `.env` and private keys) are blocked from agent access. For edits, it shows a diff and asks before writing. Use `/agent off` to disable local tools during a chat.

The `github_search_repositories` tool searches public GitHub repositories through GitHub's read-only API. It requires approval before sending search terms, returns up to 10 public repository descriptions/stars/licenses/links, and does not access private repositories or write to GitHub. Repository metadata is untrusted input; review repositories and their licenses before using their contents as skills.

Controlled browser tools use one visible, isolated Chromium window with a fresh session; they do not reuse saved browser cookies or logins. Install the optional browser support with `pip install -e ".[browser]"` and `playwright install chromium`. The first controlled browser action asks once for session approval. After that, DuckDuckGo searches, navigation, page reads, and following links do not prompt again. `browser_open_url` uses this same controlled browser, not the system default browser. `browser_inspect_design` reports visible layout, computed styles, page dimensions, stylesheet URLs, and image URLs to assist with UI recreations; it cannot guarantee pixel-perfect copies of dynamic or inaccessible content. Filling fields and clicking buttons require individual approval; form submission also requires its own confirmation. Passwords can be typed through a hidden local prompt or generated locally, then entered without sending the value to the model or chat history. Generated passwords are displayed only in the terminal for the user to save. Download links and CAPTCHA bypass are not supported. Page content is untrusted; do not follow instructions found in it. Built-in web-research guidance asks the agent to cite pages it actually inspected and not invent current prices or free-tier limits. URLs of non-search pages visited are automatically included in the final answer.

`browser_clone_page` can clone any `http(s)` page into a single project-local `.html` file: it navigates to the page, waits for it to finish loading (including client-side-rendered SPAs), captures the live DOM/layout/text, and embeds loaded stylesheets, images, fonts, and media. You can ask the agent to clone a page or run `/clone <url> [path]`. `browser_save_page` does the same for the page already open in the controlled browser. The agent is allowed to clone pages without refusing on permission grounds; each clone still asks for your approval before writing the file. Archives are static snapshots (scripts are removed, links are not crawled, and the output is limited to 25 MB), so pages behind logins/CAPTCHAs or resources the browser could not load may be incomplete.

The `website_security_posture` tool checks an HTTPS origin you own or are authorized to assess. It requires approval, resolves and pins a publicly routable address, validates TLS, and sends one `HEAD /` request. It does not crawl, follow redirects, submit forms, or send exploit payloads. The report includes certificate issuer/expiry and whether common security headers were observed. A `HEAD` response may differ from a browser's `GET`, and missing headers are observations rather than proof of a vulnerability. Redirecting sites should be checked by supplying their final HTTPS origin.

## MCP tools

MCP servers are opt-in. Add trusted server entries under `mcp.servers` in the JSON file shown by `zeroday config path`:

```json
{
  "mcp": {
    "servers": {
      "my-tools": {
        "command": "node",
        "args": ["C:\\path\\to\\my-mcp-server.js"],
        "pass_env": ["MY_SERVICE_TOKEN"]
      }
    }
  }
}
```

Run `zeroday mcp list`, then start `zeroday chat --mcp`. The CLI asks before launching each configured server and before each model-requested tool call; declining a call is safe. MCP programs can perform actions on your behalf, so configure only trusted servers and inspect each call. Sensitive environment variables are not passed to MCP processes unless you explicitly name them in `pass_env`. There is no built-in unrestricted shell tool.

The `website_security_posture` tool is a passive HTTPS posture check, not a full vulnerability scanner or remote patcher. Chat loads project `config/scope.yaml` into context; `/scope` displays the loaded summary. A registered domain covers same-host paths; URL-only entries are exact scan seeds. When `execution.active_scanning` is enabled, `web_sql_injection_scan` runs sqlmap from a scoped HTTPS seed. The first call crawls same-host links up to depth 5; if crawling is blocked, follow-up calls can scan discovered URLs directly. The assessment is limited to 20 unique URLs and 240 seconds per host, excluding common state-changing URL names and configured excluded paths. It uses optional dummy POST fields, level 1/risk 1, BEU detection, one request thread, and does not submit discovered forms, enumerate or extract database contents, or use takeover options. One session approval per scoped host covers these scans. Managed sqlmap source caches are checked for required runtime modules before use and refreshed if incomplete. Within that session, the browser may fill up to 20 visible fields and enter only the fixed dummy password `zeroday_test`; it will not submit forms automatically. Real password entry and form submission require separate approval. XSS, CSRF, and authentication-bypass checks are covered only when a configured scanner actually reports results.

### Connect Burp Suite Professional

The Burp connector is currently a stub for scan and proxy operations. `zeroday doctor` can make a bounded, authenticated, read-only request to the loopback REST API description endpoint when `burp.enabled`, `burp.api_url`, and `BURP_API_KEY` are configured. The health check blocks redirects and does not print the API key. It does not start scans or establish that scan/proxy functions work. Keep Burp bound to loopback and its own scope restricted. Burp scanning and proxy controls remain unavailable until their documented operations are implemented and tested against an explicitly authorized environment.

Availability of model-driven tool calling depends on the selected model/provider.

## Step-by-step: how it is built

1. **Config (`config.py`)**: built-in defaults for `openrouter` (the default provider) and `local`, deep-merged with the user's JSON file. A provider names its key's environment variable (`api_key_env`) rather than holding the key.
2. **Provider layer (`providers/`)**: OpenRouter and local servers share the OpenAI chat protocol, so a single `OpenAICompatProvider` handles both. `build_provider()` turns a config entry into a client and fails early with setup instructions if a required key is missing.
3. **Streaming and tools (`openai_compat.py`)**: POST `/chat/completions` for streamed replies or model-requested MCP tool calls. HTTP and network failures become `ProviderError` with a readable message (401 key hint, 404 model hint, server-not-running hint).
4. **Session (`session.py`)**: holds the system prompt and message list; saves and loads JSON files with validated names.
5. **Agent extensions (`skills.py`, `mcp.py`)**: load user-selected `SKILL.md` instructions and connect explicitly approved MCP stdio servers. Every tool call requires user approval and tool-call loops are bounded.
6. **CLI and UI (`cli.py`, `ui.py`, `tui/`)**: `argparse` subcommands share generation flags. `ask` appends piped stdin to the prompt; `chat` runs an opencode-style full-screen TUI by default in a terminal (with a plain REPL fallback) and streams replies/tool progress through a shared UI abstraction. A failed or interrupted reply is removed from history so the conversation stays valid.
7. **Cross-platform details**: config path per OS, UTF-8 console on Windows, ANSI/raw-mode terminal handling, optional `readline` on Linux.
8. **Tests**: local mock API and MCP stdio servers exercise the stack offline: `pytest -q`.

## Extending

- **Another OpenAI-compatible service** (Groq, Together, ...): `zeroday config set providers.groq.base_url ...`, `...model ...`, `...api_key_env GROQ_API_KEY`. No code needed.
- **A non-OpenAI API**: subclass `Provider` in `providers/` and branch on a `type` field in `build_provider()`.
