# eve-esi

Adopt this skill: https://proskills.md/skills/other/burnshall-ui-openclaw-eve-skill

Page: https://proskills.md/skills/other/burnshall-ui-openclaw-eve-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 23290
sha: 5f590f44da95078259673763a1a0aa4a87f49c1e
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/SKILL.md

````text
---
name: eve-esi
description: "Query and manage EVE Online characters via the ESI (EVE Swagger Interface) REST API. Performs OAuth2/PKCE browser login and stores plus auto-refreshes long-lived OAuth tokens locally in ~/.openclaw/eve-tokens.json. Read-only by default and can reach any ESI endpoint, including non-character public data; state-changing writes (mail, fittings, market orders, planetary interaction) happen only when explicitly invoked with --allow-write. Use when the user asks about EVE Online character data, wallet balance, ISK transactions, assets, skill queue, skill points, clone locations, implants, fittings, contracts, market orders, mail, industry jobs, killmails, planetary interaction, loyalty points, or any other EVE account management task."
type: scripts
includes:
  - scripts/auth_flow.py
  - scripts/get_token.py
  - scripts/esi_query.py
  - scripts/token_store.py
  - scripts/user_agent.py
  - scripts/validate_config.py
  - config/schema.json
  - config/example-config.json
  - config/esi_endpoints.json
  - references/authentication.md
  - references/endpoints.md
auth:
  method: oauth2_pkce
  provider: EVE SSO (login.eveonline.com)
  credential_storage: "~/.openclaw/eve-tokens.json"
  setup: "Run scripts/auth_flow.py once per character with a valid EVE Client ID. Ask the user which scope profile they want first (basic|pi|industry|full, default pi) — do not pick for them. Tokens are stored locally and auto-refreshed by scripts/get_token.py."
  required_for: "All authenticated ESI endpoints (wallet, assets, skills, PI, industry, etc.). Public endpoints work without auth."
env:
  - name: EVE_CLIENT_ID
    description: "EVE Developer Application Client ID (from https://developers.eveonline.com/applications). Not needed at runtime — pass directly to auth_flow.py via --client-id. Only set as env var if using $ENV: references in your dashboard config."
    required: false
    sensitive: false
  - name: EVE_TOKEN_MAIN
    description: "ESI OAuth2 access token for the main character. Not needed at runtime — scripts auto-manage tokens via ~/.openclaw/eve-tokens.json (created by auth_flow.py). Only set as env var if using $ENV: references in your dashboard config."
    required: false
    sensitive: true
  - name: EVE_REFRESH_MAIN
    description: "ESI OAuth2 refresh token for automatic access token renewal. Not needed at runtime — scripts auto-manage tokens via ~/.openclaw/eve-tokens.json. Only set as env var if using $ENV: references in your dashboard config."
    required: false
    sensitive: true
  - name: TELEGRAM_BOT_TOKEN
    description: "Telegram Bot API token for sending alerts and reports. Only needed if Telegram notifications are configured."
    required: false
    sensitive: true
  - name: TELEGRAM_CHAT_ID
    description: "Telegram chat ID where notifications are sent. Only needed if Telegram notifications are configured."
    required: false
    sensitive: false
  - name: DISCORD_WEBHOOK_URL
    description: "Discord webhook URL for sending alerts and reports. Only needed if Discord notifications are configured."
    required: false
    sensitive: true
---

# Data Handling

This skill communicates with the following external services. Every outbound
call is either a public/unauthenticated CCP endpoint, an OAuth2 flow against
the official EVE SSO, or an optional, user-configured notification sink.

- **EVE Online ESI API** (`esi.evetech.net`) — official EVE Online REST API
  (operated by CCP Games) for all character and universe data queries.
  Includes bulk lookup endpoints such as `POST /characters/affiliation/`
  and `POST /universe/names/`, which resolve public numeric IDs
  (character/corp/alliance/type IDs) to public data. These POST bodies never
  contain tokens, credentials, or private account data — only IDs that are
  already public in-game. Authenticated endpoints (wallet, assets, skills,
  etc.) send the OAuth2 bearer token only to this same host, per ESI's own
  API contract.
- **EVE SSO** (`login.eveonline.com`) — official OAuth2/PKCE authorization
  server for EVE Online. Used only for the login/token-refresh flow described
  in `references/authentication.md`.
- **EVE Developer Portal** (`developers.eveonline.com/applications`) —
  official CCP portal where the *user* registers their own EVE application
  and obtains a Client ID. This skill never calls this URL programmatically;
  it is referenced in documentation only, as the one-time manual step a user
  performs before running `scripts/auth_flow.py --client-id <...>`.
- **zKillboard API** (`zkillboard.com/api/`) — optional, public, unauthenticated.
  Only used for PVP threat-assessment features; disabled unless threat/route
  scripts are invoked.
- **Telegram Bot API** — optional, only contacted if the user sets
  `TELEGRAM_BOT_TOKEN` and configures alerts.
- **Discord Webhooks** — optional, only contacted if the user sets
  `DISCORD_WEBHOOK_URL` and configures alerts.

No character data, tokens, or credentials are sent to any third-party server
beyond the above. Telegram/Discord only receive the specific alert text the
user has configured — never raw account data or tokens.

# What this skill can access, and what it will not do

**Read-only by default.** GET requests and the documented bulk-lookup POST
endpoints run normally. Any other POST, plus PUT and DELETE, is refused unless
you pass `--allow-write` explicitly. Without that flag this skill cannot send
mail, change contacts, alter contracts, open in-game windows, or modify your
account in any way.

**Sensitive data.** The scopes you grant during `auth_flow.py` decide what the
skill can read. Several are genuinely private: wallet balance and full ISK
transaction history, complete asset lists, mail contents, contracts, clone and
implant locations, and current in-space location. Grant only the scopes your
use case needs — the skill works fine with a narrow scope set, and public
endpoints need no scopes at all.

## Agent instruction: ask before you authenticate

**Do not choose a scope profile on the user's behalf.** Scopes are granted once
and stay granted until revoked, so this is the user's decision, not yours.

Before running `auth_flow.py`, show the user the profiles and ask which one
they want:

| Profile | Scopes | Grants access to |
|---|---|---|
| `basic` | 7 | Skills, skill queue, clones, implants, location, ship, online status |
| `pi` **(default)** | 8 | `basic` plus Planetary Interaction |
| `industry` | 11 | `basic` plus assets, industry jobs, market orders, contracts |
| `full` | 17 | Everything, **including wallet balance, ISK history and mail** |

`python3 scripts/auth_flow.py --list-scope-profiles` prints the exact scope
list for each. `--scopes "<space separated>"` takes an explicit set.

If the user has not expressed a preference, use the default and say so — do not
silently pick `full` because it is convenient. If a later query fails for lack
of a scope, report which scope is missing and let the user decide whether to
re-authenticate with a wider profile.

The final gate is outside this skill: EVE SSO shows the user a consent screen
listing every requested scope, and nothing is granted until they approve it in
their browser.

**Token handling.** Access tokens are bearer credentials: anyone holding one can
read your account until it expires (~20 min). Refresh tokens are long-lived and
rotate on each use.

- Prefer `esi_query.py --char <name>`, which refreshes the token in-process. The
  token never enters argv.
- Avoid `--token "$TOKEN"` and `curl -H "Authorization: Bearer $TOKEN"`: command
  lines are visible to any local user via `ps`, and land in your shell history.
  Use `--token-stdin` when a token must come from outside.
- Never paste a token into a config file, a bug report, a log, or a chat message.

**Alert transmission.** If you configure Telegram or Discord, the alert text you
define is sent to those services in plaintext over their APIs. Do not template
raw wallet figures or asset inventories into alerts you would not want stored on
a third-party server.

# EVE Online ESI

The ESI (EVE Swagger Interface) is the official REST API for EVE Online third-party development.

- **Base URL**: `https://esi.evetech.net` — no version segment.
- **Versioning**: send `X-Compatibility-Date: 2026-08-04` on every request. CCP
  has replaced the old `/latest`, `/legacy` and `/v5` URL prefixes with this
  header ([dev blog](https://developers.eveonline.com/blog/changing-versions-v42-was-getting-out-of-hand)).
  A request that omits it does not get the newest behaviour — it gets the
  *oldest* one ESI still serves. `esi_query.py` sets the header itself; override
  it with `--compatibility-date` or `EVE_ESI_COMPATIBILITY_DATE`.
- **Spec**: `https://esi.evetech.net/meta/openapi.json` (OpenAPI 3.1) or
  `https://esi.evetech.net/meta/openapi-3.0.json` (OpenAPI 3.0). The old
  `swagger.json` is deprecated and no longer receives new routes
  ([dev blog](https://developers.eveonline.com/blog/changing-specs-from-swagger-to-openapi)).
- **Valid compatibility dates**: <https://esi.evetech.net/meta/compatibility-dates>
- **Changelog**: <https://esi.evetech.net/meta/changelog> — check this before
  bumping the compatibility date, and adjust for any `is_breaking` entry on an
  endpoint this skill uses.
- **API Explorer**: <https://developers.eveonline.com/api-explorer>
- **User-Agent**: every request identifies the skill and links its source repo,
  because CCP treats anonymous traffic as grounds for throttling. Set
  `EVE_ESI_CONTACT` to an email, `discord:name` or `eve:charname` to add the
  contact CCP would rather have.

## Skill Location

All scripts live at: `~/.openclaw/workspace/skills/eve-esi/scripts/`

Always use full paths when calling scripts:
```bash
SKILL=~/.openclaw/workspace/skills/eve-esi
```

## Authentication

Tokens are stored in `~/.openclaw/eve-tokens.json` (created by auth_flow.py, chmod 600).
All scripts (`get_token.py`, `esi_query.py`) read from this file directly — **no env vars are required for normal operation.**

**First-time setup** (once per character). The Client ID comes from the user's
own application at <https://developers.eveonline.com/applications> — it is not
stored anywhere by this skill, so ask the user for it rather than hunting for
it. Ask which scope profile they want before running this; do not choose for
them.

```bash
# 0. In the EVE application, the Callback URL must be exactly
#    http://localhost:8080/callback — the developer portal allows the http
#    scheme only for the host `localhost` and rejects 127.0.0.1 on save.
# 1. Set up SSH tunnel on your local PC:
#    ssh -L 8080:127.0.0.1:8080 user@your-server -N
# 2. Run auth flow on server (pass Client ID directly):
python3 ~/.openclaw/workspace/skills/eve-esi/scripts/auth_flow.py \
  --client-id <YOUR_CLIENT_ID> --char-name main --scope-profile <basic|pi|industry|full>
# 3. Open the shown URL in browser, log in with EVE account
```

**Preferred: let the query script handle the token.** `--char <name>` resolves and
refreshes the token in-process, so it never appears on a command line, in shell
history, or in your logs:
```bash
python3 ~/.openclaw/workspace/skills/eve-esi/scripts/esi_query.py --char main \
  --endpoint "/characters/<CHAR_ID>/wallet/" --pretty
```

Only if you genuinely need the raw token elsewhere (it expires after ~20 min,
refresh is automatic):
```bash
python3 ~/.openclaw/workspace/skills/eve-esi/scripts/get_token.py --char main
```
Do not capture it into a shell variable and pass it as `--token "$TOKEN"` —
that exposes it via `ps` and shell history. Use `--token-stdin` if a token must
be handed over.

**List authenticated characters:**
```bash
python3 ~/.openclaw/workspace/skills/eve-esi/scripts/get_token.py --list
```

For full OAuth2/PKCE details: see `references/authentication.md`.

## Calling ESI directly

The `curl` examples below are reference material for the raw API. Every one of
them goes through this helper, which sets the two headers ESI expects: a
compatibility date, so the response contract stays pinned, and a User-Agent, so
CCP can see who is calling. `esi_query.py` sets both by itself — that is one
reason it is the preferred path.

```bash
ESI="https://esi.evetech.net"
COMPAT="2026-08-04"
UA="OpenClaw-ESI-Skill/1.3.3 (+https://github.com/burnshall-ui/openclaw-eve-skill)"

esi() { curl -s -H "X-Compatibility-Date: $COMPAT" -H "User-Agent: $UA" "$@"; }
```

## Public endpoints (no auth)

```bash
# Character public info
esi "$ESI/characters/2114794365/" | python -m json.tool

# Portrait URLs
esi "$ESI/characters/2114794365/portrait/"

# Corporation history
esi "$ESI/characters/2114794365/corporationhistory/"

# Bulk affiliation lookup
esi -X POST "$ESI/characters/affiliation/" \
  -H "Content-Type: application/json" \
  -d '[2114794365, 95538921]'
```

## Character info (authenticated)

> These put the token on a command line, where `ps` and shell history expose it.
> For day-to-day use prefer `esi_query.py --char <name>` (see
> [Using the query script](#using-the-query-script)).

```bash
TOKEN="<your_access_token>"
CHAR_ID="<your_character_id>"

# Online status (scope: esi-location.read_online.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/online/"
```

## Wallet

```bash
# Balance (scope: esi-wallet.read_character_wallet.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/wallet/"

# Journal (paginated)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/wallet/journal/?page=1"

# Transactions
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/wallet/transactions/"
```

## Assets

```bash
# All assets (paginated; scope: esi-assets.read_assets.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/assets/?page=1"

# Resolve item locations
esi -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '[1234567890, 9876543210]' \
  "$ESI/characters/$CHAR_ID/assets/locations/"

# Resolve item names
esi -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '[1234567890]' \
  "$ESI/characters/$CHAR_ID/assets/names/"
```

## Skills

```bash
# All trained skills + total SP (scope: esi-skills.read_skills.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/skills/"

# Skill queue (scope: esi-skills.read_skillqueue.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/skillqueue/"

# Attributes (intelligence, memory, etc.)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/attributes/"
```

## Location and ship

```bash
# Current location (scope: esi-location.read_location.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/location/"

# Current ship (scope: esi-location.read_ship_type.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/ship/"
```

## Clones and implants

```bash
# Jump clones + home station (scope: esi-clones.read_clones.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/clones/"

# Active implants (scope: esi-clones.read_implants.v1)
esi -H "Authorization: Bearer $TOKEN" "$ESI/characters/$CHAR_ID/implants/"
```

## More endpoints

For contracts, fittings, mail, industry, killmails, market orders, mining, planetary interaction, loyalty points, notifications, blueprints, standings, and all other character endpoints, see [references/endpoints.md](references/endpoints.md).

## Dashboard Config

The skill defines and validates a config format for alerts, reports and market
tracking. It does **not** execute any of it: there is no poller, no scheduler
and no notification sender in this skill. Do not tell the user their alerts are
running because a config exists — the config is a description that some other
automation has to act on. `validate_config.py` checks that a config is well
formed and that the stored token actually carries the scopes it references.

- **Schema**: [config/schema.json](config/schema.json) — full JSON Schema with all fields, types, and defaults
- **Example**: [config/example-config.json](config/example-config.json) — ready-to-use template

### Features

| Module | Description |
|--------|-------------|
| **Alerts** | Real-time polling for war decs, structure attacks, skill completions, wallet changes, industry jobs, PI extractors, killmails, contracts, clone jumps, mail |
| **Reports** | Cron-scheduled summaries: net worth, skill queue, industry, market orders, wallet, assets |
| **Market** | Price tracking with absolute thresholds and trend detection |

### Security

Do **not** write tokens into the dashboard config file. There are two supported
places for credentials, and they do not conflict:

| Location | What lives there | Who writes it |
|----------|------------------|---------------|
| `~/.openclaw/eve-tokens.json` | The canonical token store: refresh tokens + client IDs, one entry per character. Created `chmod 600`, rewritten atomically, lock-protected. | `auth_flow.py` / `get_token.py` |
| Dashboard config JSON | No secrets. Reference env vars if a value is unavoidable. | You |

The scripts read the token store directly, so a normal setup needs **no**
credentials in the config file and no env vars at all. Only use `$ENV:`
references if you drive the dashboard from a system that cannot reach the
token store:

```json
{
  "token": "$ENV:EVE_TOKEN_MAIN",
  "refresh_token": "$ENV:EVE_REFRESH_MAIN"
}
```

The config file should live outside the workspace (e.g. `~/.openclaw/eve-dashboard-config.json`).

### Validate a config

```bash
python scripts/validate_config.py path/to/config.json

# Show example config
python scripts/validate_config.py --example

# Show JSON schema
python scripts/validate_config.py --schema
```

## Using the query script

Pass `--char <name>` and the script refreshes the stored token itself. The token
never appears on a command line, so `ps` and shell history cannot leak it.

```bash
SKILL=~/.openclaw/workspace/skills/eve-esi
# Replace 'main' with your --char-name if you authenticated under a different name.
CHAR_ID=$(python3 $SKILL/scripts/get_token.py --char main --char-id)

# Simple query
python3 $SKILL/scripts/esi_query.py --char main --endpoint "/characters/$CHAR_ID/wallet/" --pretty

# Fetch all pages of assets
python3 $SKILL/scripts/esi_query.py --char main --endpoint "/characters/$CHAR_ID/assets/" --pages --pretty

# Bulk lookup POST (asset names) — a read-only lookup, no --allow-write needed
python3 $SKILL/scripts/esi_query.py --char main --endpoint "/characters/$CHAR_ID/assets/names/" \
  --method POST --body '[1234567890]' --pretty
```

If you must supply a token from elsewhere, pipe it in rather than passing `--token`:

```bash
printf '%s\n' "$TOKEN" | python3 $SKILL/scripts/esi_query.py --token-stdin --endpoint /characters/$CHAR_ID/wallet/
```

## Best practices

- **Caching**: respect the `Expires` header; do not poll before it expires.
  Polling around the cache is treated as circumventing it and can get you banned.
- **Error limits**: monitor `X-ESI-Error-Limit-Remain`; back off when low. A 4xx
  costs five times what a 2xx costs, so validate input before sending it.
- **Rate limits**: routes under bucket limiting report `X-Ratelimit-Remaining`
  and answer with `429` plus `Retry-After` once the bucket is empty.
  `esi_query.py` honours both, and warns once a bucket drops below 20%.
- **User-Agent**: always set a descriptive User-Agent with contact info.
- **Pagination**: check the `X-Pages` response header; iterate with `?page=N`.
- **Versioning**: do not use URL prefixes. `/latest/`, `/legacy/`, `/dev/` and
  `/v5/` are deprecated — send the `X-Compatibility-Date` header instead, and
  pin it to a date you have actually reviewed. `esi_query.py` strips a version
  prefix if one reaches it anyway.
- **Scheduling**: stagger periodic jobs rather than firing them all on `*/5`.

## Threat Assessment & Route Planning

The skill provides threat intelligence for PI systems in low/null-sec space. Data sources: ESI (kills, jumps, FW, incursions) and zKillboard (PVP activity).

### ESI Threat Endpoints

```bash
SKILL=~/.openclaw/workspace/skills/eve-esi

# System kills (last hour) — all or filtered
python3 $SKILL/scripts/esi_query.py --action system_kills --pretty
python3 $SKILL/scripts/esi_query.py --action system_kills --system-ids 30002537,30045337 --pretty

# System jump traffic (last hour)
python3 $SKILL/scripts/esi_query.py --action system_jumps --system-ids 30045337 --pretty

# System info (name, security status)
python3 $SKILL/scripts/esi_query.py --action system_info --system-id 30002537 --pretty

# Route planning (flags: secure, shortest, insecure)
python3 $SKILL/scripts/esi_query.py --action route_plan --origin 30000142 --destination 30002537 --route-flag secure --pretty

# Character location (requires auth)
python3 $SKILL/scripts/esi_query.py --action character_location --char main --character-id $CHAR_ID --pretty

# Faction warfare systems
python3 $SKILL/scripts/esi_query.py --action fw_systems --pretty

# Active incursions
python3 $SKILL/scripts/esi_query.py --action incursions --pretty
```

### Threat Assessment Scripts (Workspace)

> **Hinweis:** Die Workspace-Skripte (`threat_query.py`, `cache_threat_data.py`, `cache_market_prices.py`) sind Referenz-Beschreibungen und müssen erst im Agent-Workspace erstellt werden, bevor sie genutzt werden können.

These scripts live in `~/.openclaw/workspace/scripts/` (not in the skill repo):

```bash
# Threat level for specific systems
python3 ~/.openclaw/workspace/scripts/threat_query.py --action threat_assessment --system-ids 30002537,30045337

# Threat for all PI systems across all characters
python3 ~/.openclaw/workspace/scripts/threat_query.py --action threat_assessment_pi

# Route with per-system threat annotation
python3 ~/.openclaw/workspace/scripts/threat_query.py --action route_annotated --origin 30000142 --destination 30002537

# Route from character's current location
python3 ~/.openclaw/workspace/scripts/threat_query.py --action route_annotated --character main --destination 30045337

# Full PI + Threat morning briefing
python3 ~/.openclaw/workspace/scripts/threat_query.py --action pi_briefing
```

### Threat Levels

| Level | Score | Meaning |
|-------|-------|---------|
| `low` | 0-15 | Normaler PI-Betrieb |
| `medium` | 15-40 | Schnell rein, schnell raus |
| `high` | 40-80 | Nur mit Scout/Cloak |
| `critical` | 80+ | NICHT reinfliegen |

### Threat Cache

Threat data is cached in Redis (30min TTL for ESI, 1h for zKillboard). The cache is updated every 30 minutes via cron:

```bash
# Update cache manually
python3 ~/.openclaw/workspace/scripts/cache_threat_data.py

# Show cached threat data
python3 ~/.openclaw/workspace/scripts/cache_threat_data.py --check
```

## Resolving type IDs

ESI returns numeric type IDs (e.g. for ships, items, skills). Resolve names via:

```bash
SKILL=~/.openclaw/workspace/skills/eve-esi

# Single type
python3 $SKILL/scripts/esi_query.py --endpoint "/universe/types/587/" --pretty

# Bulk names (up to 1000 IDs)
python3 $SKILL/scripts/esi_query.py --endpoint "/universe/names/" \
  --method POST --body '[587, 638, 11393]' --pretty
```
````

## File: README.md
size: 18021
sha: 59ef0489103577490c5fc2eb2e9af7ab0057dab8
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/README.md

````text
# EVE ESI Skill for OpenClaw

> Ask your agent what New Eden is up to — wallet, skills, industry, and what
> your planets are doing while you are docked somewhere else entirely.

An [OpenClaw](https://openclaw.ai) skill for the
[EVE Online ESI API](https://developers.eveonline.com/api-explorer)
(EVE Swagger Interface). Read-only by default, no pip dependencies, tokens
stay on your machine.

## Contents

- [What it does](#what-it-does) · [Install](#install) · [Authenticate](#authenticate) · [Quick start](#quick-start)
- [Planetary Interaction](#planetary-interaction) · [Market prices](#market-prices) · [Threat assessment](#threat-assessment-and-route-planning) · [Dashboard config](#dashboard-config)
- [Security](#security) · [Reference](#reference) · [Links](#links)

---

## What it does

| | |
|---|---|
| **Authentication** | EVE SSO OAuth2 with PKCE, no client secret. Tokens auto-refresh and rotate. |
| **Multi-character** | Unlimited characters under named keys — `main`, `alt1`, whatever you call them. |
| **Planetary Interaction** | Extractor timers, storage fill, factory routing, and a parsed "needs attention" verdict per planet. |
| **Market** | Global adjusted/average prices, plus live Jita buy/sell for a single type. |
| **Threat assessment** | System scoring from ESI kills and jumps combined with zKillboard PVP data. |
| **Route planning** | Routes annotated with a per-system threat level. |
| **ESI queries** | Generic helper with pagination, rate-limit handling and error recovery. |
| **Dashboard config** | A validated JSON Schema vocabulary for alerts, reports and price tracking. Defines them; does not run them. |

## Install

```bash
cd ~/.openclaw/workspace/skills
git clone https://github.com/burnshall-ui/openclaw-eve-skill eve-esi
```

Python 3.10+, standard library only for everything in this repo.

## Authenticate

**Before you start**, register an application at
[developers.eveonline.com](https://developers.eveonline.com/applications):

1. Callback URL: `http://localhost:8080/callback`. The portal accepts the `http`
   scheme only for the host `localhost` — `127.0.0.1` is refused on save.
2. Enable the scopes you may want under **Enabled Scopes**. A scope profile can
   only ask for what the application already has enabled, so enabling a scope
   here does not grant it — it just makes it available to request. Planetary
   Interaction needs `esi-planets.manage_planets.v1`; to keep `--scope-profile
   full` usable later, enable all 17 listed under [Scope profiles](#scope-profiles).
3. Note the **Client ID** (with PKCE there is no client secret to keep)

Then authenticate once per character:

```bash
# On a remote server, tunnel the callback port to your browser first:
ssh -L 8080:127.0.0.1:8080 user@your-server -N

python3 scripts/auth_flow.py --client-id <YOUR_CLIENT_ID> --char-name main
# Open the printed URL and log in with your EVE account
```

**Choose how much access to grant.** Scopes are granted once and stay granted
until you revoke them, so the default asks for the narrow set:

| Profile | Scopes | Grants access to |
|---|---|---|
| `basic` | 7 | Skills, skill queue, clones, implants, location, ship, online status |
| `pi` **(default)** | 8 | `basic` plus Planetary Interaction |
| `industry` | 11 | `basic` plus assets, industry jobs, market orders, contracts |
| `full` | 17 | Everything, **including wallet balance, ISK history and mail** |

```bash
python3 scripts/auth_flow.py --list-scope-profiles          # exact scopes per profile
python3 scripts/auth_flow.py --client-id <ID> --scope-profile full
python3 scripts/auth_flow.py --client-id <ID> --scopes "esi-skills.read_skills.v1"
```

The flow prints what it is about to request before opening the browser, and EVE
SSO shows you the same list on its consent screen. Nothing is granted until you
approve it there.

Tokens land in `~/.openclaw/eve-tokens.json` (`chmod 600`) and rotate on every
use. Repeat with a different `--char-name` for each alt:

```bash
python3 scripts/auth_flow.py --client-id <CLIENT_ID> --char-name alt1
python3 scripts/get_token.py --list      # who is authenticated?
```

## Quick start

`--char <name>` resolves and refreshes the token **in-process**, so it never
touches a command line, your shell history, or a log file. Prefer it over
passing `--token`.

```bash
SKILL=~/.openclaw/workspace/skills/eve-esi
CHAR_ID=<your_character_id>

# Wallet balance
python3 $SKILL/scripts/esi_query.py --char main \
  --endpoint "/characters/$CHAR_ID/wallet/" --pretty

# Skill queue
python3 $SKILL/scripts/esi_query.py --char main \
  --endpoint "/characters/$CHAR_ID/skillqueue/" --pretty

# Every asset you own, following pagination
python3 $SKILL/scripts/esi_query.py --char main \
  --endpoint "/characters/$CHAR_ID/assets/" --pages --pretty

# Planets, and what needs attention on them
python3 $SKILL/scripts/esi_query.py --action pi_planets --char main --character-id $CHAR_ID --pretty
python3 $SKILL/scripts/esi_query.py --action pi_status  --char main --character-id $CHAR_ID --pretty

# Market — public data, no authentication needed
python3 $SKILL/scripts/esi_query.py --action jita_price --type-id 2393 --pretty
python3 $SKILL/scripts/esi_query.py --action market_price_bulk --pretty
```

## Planetary Interaction

High-level actions that turn raw ESI output into something you can act on.

```bash
# All planets for a character
python3 $SKILL/scripts/esi_query.py --action pi_planets \
  --char main --character-id $CHAR_ID --pretty

# Extractor timers, storage fill, attention flags
python3 $SKILL/scripts/esi_query.py --action pi_status \
  --char main --character-id $CHAR_ID --pretty

# One planet in detail
python3 $SKILL/scripts/esi_query.py --action pi_planet_detail \
  --char main --character-id $CHAR_ID --planet-id <PLANET_ID> --pretty
```

`pi_status` returns per planet:

| Field | Description |
|---|---|
| `planet_name` | Resolved planet name (e.g. "Ikoskio VII") |
| `extractors` | Product, expiry time, hours remaining, status |
| `storage_fill_pct` | Estimated launchpad/storage fill |
| `factories` | Input/output product routing |
| `needs_attention` | `true` when an extractor runs dry in < 6 h or storage exceeds 80 % |
| `action_required` | Plain-language description of what to do |

**A limit worth knowing up front:** ESI exposes PI as **read-only**. This skill
will tell you that an extractor expires in four hours and that your launchpad
is nearly full — it cannot restart the extractor, reroute a product, or touch
the layout. That part still happens in the client.

## Market prices

```bash
# Adjusted and average prices for every type in the game
python3 $SKILL/scripts/esi_query.py --action market_price_bulk --pretty

# Live Jita book for one type (9832 = Coolant)
python3 $SKILL/scripts/esi_query.py --action jita_price --type-id 9832 --pretty
```

`jita_price` reports lowest sell, highest buy, the spread and order counts for
The Forge.

## Threat assessment and route planning

Intended for deciding whether that low-sec PI run is worth it right now.

```bash
python3 $SKILL/scripts/esi_query.py --action system_kills --system-ids 30002537 --pretty
python3 $SKILL/scripts/esi_query.py --action system_jumps --system-ids 30002537 --pretty
python3 $SKILL/scripts/esi_query.py --action system_info  --system-id 30002537 --pretty

python3 $SKILL/scripts/esi_query.py --action route_plan \
  --origin 30000142 --destination 30002537 --route-flag secure --pretty

python3 $SKILL/scripts/esi_query.py --action character_location \
  --char main --character-id $CHAR_ID --pretty

python3 $SKILL/scripts/esi_query.py --action fw_systems --pretty
python3 $SKILL/scripts/esi_query.py --action incursions --pretty
```

**Threat levels**

| Level | Score | Read as |
|---|---|---|
| `low` | 0–15 | Normal operations |
| `medium` | 15–40 | Quick in, quick out |
| `high` | 40–80 | Scout or cloak only |
| `critical` | 80+ | Do not enter |

**Data sources** — all public, none require authentication:

| Source | Data |
|---|---|
| ESI `/universe/system_kills/` | Ship, pod and NPC kills, last hour |
| ESI `/universe/system_jumps/` | Jump traffic, last hour |
| ESI `/route/{origin}/{destination}/` | Route planning |
| ESI `/fw/systems/` | Faction Warfare contested systems |
| ESI `/incursions/` | Active NPC incursions |
| zKillboard API | PVP kills with value, last 24 h |

The raw data above is what this skill provides, and the `--action` helpers for
it work today. The composite *scoring* layer on top — `threat_query.py`,
`cache_threat_data.py` — is **not written yet**: `SKILL.md` describes the
interface it should have, as a specification for something you build in your
agent workspace. Nothing named there ships with this repo.

## Dashboard config

**What ships here is the config format and its validator — not a runner.** The
skill has no poller, no scheduler and no code that sends a message anywhere;
`grep` it for yourself. The tables below are the vocabulary your agent's own
automation can use, and the validator tells you whether a config is well formed
and whether your token covers the scopes it asks for. Wiring it to something
that actually polls on a schedule and delivers to Telegram or Discord is work
that lives in your agent workspace, and you have to write it.

```bash
cp config/example-config.json ~/.openclaw/eve-dashboard-config.json
# edit it — use $ENV:VARIABLE_NAME for anything secret, never inline a token
python3 scripts/validate_config.py ~/.openclaw/eve-dashboard-config.json
```

Full schema in [config/schema.json](config/schema.json), endpoint presets in
[config/esi_endpoints.json](config/esi_endpoints.json).

| Alerts | | Reports | |
|---|---|---|---|
| `war_declared` | New war declaration | `net_worth` | ISK across wallet and assets |
| `structure_under_attack` | Structure attacked | `skill_queue` | Current training status |
| `skill_complete` | Skill finished training | `industry_jobs` | Active manufacturing and research |
| `wallet_large_deposit` | Deposit above a threshold | `market_orders` | Open buy and sell orders |
| `industry_job_complete` | Job done | `wallet_summary` | Recent transactions |
| `pi_extractor_expired` | Extraction head expired | `assets_summary` | Top asset locations by value |
| `killmail` | New killmail | | |
| `contract_expired` | Contract expired | | |

## Security

This skill holds credentials to your account. What that means concretely:

- Tokens live in `~/.openclaw/eve-tokens.json` with `chmod 600`. Refresh tokens
  rotate on every use, as EVE SSO intends.
- PKCE means there is no client secret to leak in the first place.
- **Access tokens expire in about 20 minutes. Refresh tokens do not.** Anything
  that prints a refresh token — logs, transcripts, CI output — hands over
  lasting access. `get_token.py --json` redacts it unless you explicitly pass
  `--include-refresh-token`.
- Prefer `--char`; it keeps the token out of `ps` output and shell history.
  Use `--token-stdin` when a token genuinely has to be handed over.
- `.gitignore` blocks `eve-tokens.json`, anything matching `*credentials*`, and
  the dashboard config. **Never commit real tokens.**
- Writes to your account are refused unless you pass `--allow-write`.

Access can be revoked at any time at
[EVE Third Party Applications](https://community.eveonline.com/support/third-party/).

## Reference

### Scope profiles

Scopes are granted once at login and persist until the token is revoked, so the
login asks for a profile rather than for everything. **The default is `pi` with
8 scopes** — notably no wallet and no mail. All profiles build on `basic`, and
`full` contains every other one, but `pi` and `industry` are siblings: choosing
`industry` does *not* give you the PI scope.

```bash
python3 scripts/auth_flow.py --list-scope-profiles   # see exactly what each asks for
python3 scripts/auth_flow.py --client-id <ID> --char-name main --scope-profile full
```

| Profile | Scopes | Adds |
|---|---|---|
| `basic` | 7 | skills, skill queue, clones, implants, location, ship, online status |
| `pi` *(default)* | 8 | `esi-planets.manage_planets.v1` |
| `industry` | 11 | assets, industry jobs, market orders, contracts |
| `full` | 17 | wallet, mail, notifications, killmails, jump fatigue |

`--scopes "<space-separated list>"` overrides the profile entirely. Before it
opens the browser, `auth_flow.py` prints the exact scope list it is about to
request.

> **`full` is not every scope ESI has.** It covers the 17 scopes the skill's own
> high-level features need. [`references/endpoints.md`](references/endpoints.md)
> documents 37 — the remaining 20 (contacts, fittings, mining, loyalty points,
> bookmarks, calendar, standings, blueprints, medals, titles, fleet, structure
> search, and the four `write_*`/`send_mail` ones) are in **no** profile.
> The raw endpoint mode can address those routes, but ESI will reject them with
> a missing-scope error unless you requested them explicitly and enabled them on
> your EVE application. The four write scopes are left out on purpose: this
> skill is read-only by default.
>
> To take a profile and add to it, pass the union yourself — `--scopes` replaces
> the profile rather than extending it:
>
> ```bash
> python3 scripts/auth_flow.py --list-scope-profiles      # copy the full list
> python3 scripts/auth_flow.py --client-id <ID> --char-name main \
>   --scopes "<the 17 from full> esi-fittings.read_fittings.v1 esi-industry.read_character_mining.v1"
> ```

> Despite its name, `esi-planets.manage_planets.v1` is the scope ESI requires
> for *reading* PI colony data; this skill never writes to a colony. The name is
> CCP's, and the real consent gate is the EVE SSO page, which shows you the same
> list before you approve it.

### ESI compliance

- No versioned URL prefixes. Requests go to `https://esi.evetech.net` and carry
  `X-Compatibility-Date: 2026-08-04`, per CCP's move away from `/latest` and
  `/v5`. Override with `--compatibility-date` or `EVE_ESI_COMPATIBILITY_DATE`.
- Every request — ESI and SSO alike — sends a `User-Agent` naming the skill,
  its version and this repository. Set `EVE_ESI_CONTACT` to add an email or
  `discord:name`.
- `429` responses are retried after `Retry-After`, `420` after the error-limit
  reset, three attempts at most. A rate limit bucket below 20% warns on stderr.
- The `Expires` header is surfaced rather than worked around.

### Action parameters

- `--action` accepts `pi_planets`, `pi_planet_detail`, `pi_status`,
  `market_price_bulk`, `jita_price`, `system_kills`, `system_jumps`,
  `system_info`, `route_plan`, `character_location`, `fw_systems`, `incursions`
- `--character-id` — required for PI actions and `character_location`
- `--planet-id` — required for `pi_planet_detail`
- `--type-id` — required for `jita_price`
- `--system-id` / `--system-ids` — threat actions
- `--origin`, `--destination`, `--route-flag` — `route_plan`

### Repository layout

```
eve-esi/
├── SKILL.md                  # instructions the agent loads
├── scripts/
│   ├── auth_flow.py          # one-time EVE SSO OAuth2 PKCE login
│   ├── get_token.py          # token refresh helper
│   ├── esi_query.py          # ESI queries + high-level PI/market actions
│   ├── token_store.py        # locked read/write of the token file
│   ├── user_agent.py         # the User-Agent every outbound call sends
│   └── validate_config.py    # dashboard config validator
├── config/
│   ├── schema.json           # JSON Schema for the dashboard config
│   ├── example-config.json   # template
│   └── esi_endpoints.json    # PI and market endpoint presets
├── references/
│   ├── authentication.md     # EVE SSO OAuth2 + PKCE in detail
│   └── endpoints.md          # endpoint index with data-sensitivity notes
└── tests/
    └── test_regressions.py
```

### Requirements

- Python 3.10+ — standard library only for core ESI queries
- OpenClaw gateway, for agent integration
- Redis and the `redis` package — **optional**, only for PI price caching

<details>
<summary>Optional: Redis price cache</summary>

Caches PI market prices with a one-hour TTL. Without it, prices are fetched
live from ESI on every request.

```bash
sudo apt install redis-server
sudo systemctl enable redis-server
pip3 install redis
redis-cli ping   # → PONG
```

The companion script `cache_market_prices.py` does not exist yet — it is a
sketch of what you would write in your agent workspace, using the key schema
`eve:market:price:{type_id}`. Nothing in this repo reads or writes Redis.

</details>

## Links

- [EVE ESI API Explorer](https://developers.eveonline.com/api-explorer)
- [EVE Developer Portal](https://developers.eveonline.com/applications)
- [Revoke third-party access](https://community.eveonline.com/support/third-party/)
- [OpenClaw Docs](https://docs.openclaw.ai)

---

MIT licensed — see [LICENSE](LICENSE). This is a non-commercial, free tool; it
asks for no payment and carries no advertising.

EVE Online and the EVE logo are the registered trademarks of CCP hf. All rights
are reserved worldwide. All other trademarks are the property of their
respective owners. EVE Online, the EVE logo, EVE and all associated logos and
designs are the intellectual property of CCP hf. All artwork, screenshots,
characters, vehicles, storylines, world facts or other recognizable features of
the intellectual property relating to these trademarks are likewise the
intellectual property of CCP hf. CCP hf. has granted permission to this project
to use EVE Online and all associated logos and designs for promotional and
information purposes on its website but does not endorse, and is not in any way
affiliated with, this project. CCP is in no way responsible for the content on
or functioning of this software, nor can it be liable for any damage arising
from the use of it.

Fly safe. o7
````

## File: scripts/auth_flow.py
size: 10913
sha: c83e85f54e72e95a3f0325f46bd79d0f01b05a2b
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/scripts/auth_flow.py

```text
#!/usr/bin/env python3
"""EVE SSO OAuth2 PKCE authentication flow.

Usage:
    python auth_flow.py --client-id <CLIENT_ID> [--char-name <NAME>] [--port 8080]

Stores refresh token to $OPENCLAW_STATE_DIR/eve-tokens.json (default: ~/.openclaw/)
"""
import argparse
import base64
import hashlib
import http.server
import json
import os
import secrets
import sys
import threading
import urllib.error
import urllib.parse
import urllib.request

from token_store import get_tokens_file, load_tokens, save_tokens_unlocked, token_file_lock
from user_agent import USER_AGENT

class AuthFlowError(Exception):
    """Raised when the OAuth authentication flow fails."""

# Scopes are granted once at login and persist until the token is revoked at
# https://community.eveonline.com/support/third-party/ — so the default asks for
# the narrow set needed to monitor planets, not for everything the API offers.
# Widen deliberately with --scope-profile or --scopes.

_BASIC = [
    "esi-skills.read_skills.v1",
    "esi-skills.read_skillqueue.v1",
    "esi-clones.read_clones.v1",
    "esi-clones.read_implants.v1",
    "esi-location.read_location.v1",
    "esi-location.read_ship_type.v1",
    "esi-location.read_online.v1",
]

SCOPE_PROFILES = {
    # Character basics: training, clones, where you are and in what.
    "basic": _BASIC,
    # Default. Planetary Interaction monitoring on top of the basics.
    "pi": _BASIC + [
        "esi-planets.manage_planets.v1",
    ],
    # Production and hauling: what you own, what you are building and selling.
    "industry": _BASIC + [
        "esi-assets.read_assets.v1",
        "esi-industry.read_character_jobs.v1",
        "esi-markets.read_character_orders.v1",
        "esi-contracts.read_character_contracts.v1",
    ],
    # Everything this skill knows how to use — including wallet and mail.
    # Only pick this if you actually want an agent reading your correspondence.
    "full": _BASIC + [
        "esi-planets.manage_planets.v1",
        "esi-assets.read_assets.v1",
        "esi-industry.read_character_jobs.v1",
        "esi-markets.read_character_orders.v1",
        "esi-contracts.read_character_contracts.v1",
        "esi-wallet.read_character_wallet.v1",
        "esi-characters.read_notifications.v1",
        "esi-characters.read_fatigue.v1",
        "esi-killmails.read_killmails.v1",
        "esi-mail.read_mail.v1",
    ],
}

DEFAULT_SCOPE_PROFILE = "pi"

def pkce_pair():
    verifier = secrets.token_urlsafe(64)
    digest = hashlib.sha256(verifier.encode()).digest()
    challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
    return verifier, challenge

def exchange_code(code, verifier, client_id, redirect_uri):
    data = urllib.parse.urlencode({
        "grant_type": "authorization_code",
        "code": code,
        "client_id": client_id,
        "code_verifier": verifier,
        "redirect_uri": redirect_uri,
    }).encode()
    req = urllib.request.Request(
        "https://login.eveonline.com/v2/oauth/token",
        data=data,
        headers={
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": USER_AGENT,
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
        raise AuthFlowError(f"Token exchange failed ({e.code}): {body}")
    except urllib.error.URLError as e:
        raise AuthFlowError(f"Could not connect to EVE login server: {e.reason}")

def verify_token(access_token):
    # /v2/oauth/verify is what the SSO metadata document at
    # https://login.eveonline.com/.well-known/oauth-authorization-server names as
    # the userinfo endpoint; the unversioned /oauth/verify is the older one.
    req = urllib.request.Request(
        "https://login.eveonline.com/v2/oauth/verify",
        headers={
            "Authorization": f"Bearer {access_token}",
            "User-Agent": USER_AGENT,
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
        raise AuthFlowError(f"Token verification failed ({e.code}): {body}")
    except urllib.error.URLError as e:
        raise AuthFlowError(f"Could not connect to EVE login server: {e.reason}")

def main():
    parser = argparse.ArgumentParser(description="EVE SSO OAuth2 PKCE auth flow")
    parser.add_argument("--client-id", required=True,
                        help="EVE Developer App Client ID")
    parser.add_argument("--char-name", default="main",
                        help="Short name to save this character as (e.g. 'main', 'alt1')")
    parser.add_argument("--port", type=int, default=8080,
                        help="Local callback port (default: 8080)")
    parser.add_argument("--timeout", type=int, default=300,
                        help="Seconds to wait for browser callback (default: 300)")
    parser.add_argument("--scope-profile", default=DEFAULT_SCOPE_PROFILE,
                        choices=sorted(SCOPE_PROFILES),
                        help=f"Which permissions to request (default: {DEFAULT_SCOPE_PROFILE}). "
                             "'full' includes wallet and mail.")
    parser.add_argument("--scopes",
                        help="Explicit space-separated scope list, overrides --scope-profile")
    parser.add_argument("--list-scope-profiles", action="store_true",
                        help="Show what each profile requests, then exit")
    args = parser.parse_args()

    if args.list_scope_profiles:
        for name, scopes in SCOPE_PROFILES.items():
            marker = "  (default)" if name == DEFAULT_SCOPE_PROFILE else ""
            print(f"\n{name}{marker} — {len(scopes)} scopes")
            for s in scopes:
                print(f"    {s}")
        return

    if args.scopes:
        scopes = args.scopes.split()
    else:
        scopes = SCOPE_PROFILES[args.scope_profile]
    scope_string = " ".join(scopes)

    # Say out loud what is about to be handed over — these persist until revoked.
    source = "--scopes" if args.scopes else f"profile '{args.scope_profile}'"
    print(f"Requesting {len(scopes)} scopes ({source}):")
    for s in scopes:
        print(f"  {s}")
    print("\nThese remain granted until you revoke them at")
    print("https://community.eveonline.com/support/third-party/")
    if not args.scopes and args.scope_profile != "full":
        others = [n for n in SCOPE_PROFILES if n != args.scope_profile]
        print(f"Need more? --scope-profile {{{','.join(sorted(others))}}} "
              "or --list-scope-profiles\n")
    else:
        print()

    verifier, challenge = pkce_pair()
    state = secrets.token_urlsafe(16)
    # Must be the literal host `localhost`, not 127.0.0.1: the EVE developer
    # portal only accepts the http scheme for `localhost` and rejects an IP
    # address outright, so a callback URL with 127.0.0.1 cannot be registered
    # in the first place. SSO then matches this string exactly against what is
    # registered. The callback server below still binds to 127.0.0.1 — that is
    # the address the SSH tunnel forwards to, and is unrelated to the name the
    # browser resolves.
    redirect_uri = f"http://localhost:{args.port}/callback"

    auth_url = (
        "https://login.eveonline.com/v2/oauth/authorize/?"
        + urllib.parse.urlencode({
            "response_type": "code",
            "redirect_uri": redirect_uri,
            "client_id": args.client_id,
            "scope": scope_string,
            "state": state,
            "code_challenge": challenge,
            "code_challenge_method": "S256",
        })
    )

    result = {}

    class CallbackHandler(http.server.BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            pass  # suppress default logs

        def do_GET(self):
            parsed = urllib.parse.urlparse(self.path)
            if parsed.path != "/callback":
                self.send_response(404)
                self.end_headers()
                return

            params = urllib.parse.parse_qs(parsed.query)
            code = params.get("code", [None])[0]
            got_state = params.get("state", [None])[0]

            if got_state != state:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b"State mismatch. Try again.")
                return

            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            self.wfile.write(b"<h2>Authorized! You can close this tab.</h2>")
            result["code"] = code
            threading.Thread(target=self.server.shutdown).start()

    try:
        httpd = http.server.HTTPServer(("127.0.0.1", args.port), CallbackHandler)
    except OSError as e:
        raise AuthFlowError(
            f"Could not start callback server on 127.0.0.1:{args.port}: {e}"
        ) from e

    print(f"\n{'='*60}")
    print("EVE SSO Auth Flow")
    print(f"{'='*60}")
    print(f"\nIf running on a remote server, set up SSH tunnel first:")
    print(f"  ssh -L {args.port}:127.0.0.1:{args.port} user@your-server -N")
    print(f"\nThen open this URL in your browser:")
    print(f"\n  {auth_url}\n")
    print(f"Waiting for callback on port {args.port} (timeout: {args.timeout}s)...")
    print(f"{'='*60}\n")

    timeout_timer = threading.Timer(args.timeout, httpd.shutdown)
    timeout_timer.daemon = True
    timeout_timer.start()
    httpd.serve_forever()
    timeout_timer.cancel()

    if not result.get("code"):
        raise AuthFlowError("Timed out waiting for browser callback.")

    print("Auth code received. Exchanging for tokens...")
    token_data = exchange_code(result["code"], verifier, args.client_id, redirect_uri)

    print("Verifying token...")
    char_info = verify_token(token_data["access_token"])

    char_id = char_info["CharacterID"]
    char_name = char_info["CharacterName"]

    with token_file_lock():
        tokens = load_tokens()
        tokens["characters"][args.char_name] = {
            "character_id": char_id,
            "character_name": char_name,
            "client_id": args.client_id,
            "refresh_token": token_data["refresh_token"],
        }
        save_tokens_unlocked(tokens)

    print(f"\n✓ Authenticated as: {char_name} (ID: {char_id})")
    print(f"✓ Saved as key: '{args.char_name}'")
    print(f"✓ Tokens stored in: {get_tokens_file()}")
    print(f"\nUsage:")
    print(f"  python get_token.py --char {args.char_name}")

if __name__ == "__main__":
    try:
        main()
    except AuthFlowError as e:
        print(f"ERROR: {e}", file=sys.stderr)
        sys.exit(1)
```

## File: scripts/esi_query.py
size: 39506
sha: 73f4c71d17bdc725a46202d0da787624f1d0011f
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/scripts/esi_query.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/scripts/esi_query.py

## File: scripts/get_token.py
size: 7818
sha: afdca49be1b727934008eca9c49ad160dd0fa3b2
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/scripts/get_token.py

```text
#!/usr/bin/env python3
"""EVE ESI token refresh helper.

Reads refresh_token from $OPENCLAW_STATE_DIR/eve-tokens.json (default: ~/.openclaw/) and returns a fresh access_token.

Usage:
    python get_token.py --char main          # prints a short-lived access token to stdout
    python get_token.py --char main --json   # token response as JSON, refresh_token redacted
    python get_token.py --char main --char-id  # prints only the character ID
    python get_token.py --list               # list all stored characters

Security note:
    Anything printed here goes to stdout and can end up in shell history, logs,
    CI output or agent chat transcripts. Prefer `esi_query.py --char main`,
    which resolves the token in-process and never prints it.

    Access tokens are short-lived (~20 minutes). The refresh token is NOT:
    it is a long-lived bearer credential that grants continued access to the
    account. `--json` therefore redacts it unless you pass
    `--include-refresh-token` explicitly.

    Capturing a printed token into a shell variable and passing it on a command
    line (`--token "$TOKEN"`) additionally exposes it via `ps` and shell history.
"""
import argparse
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request

from token_store import get_tokens_file, load_tokens, save_tokens_unlocked, token_file_lock
from user_agent import USER_AGENT

class TokenError(Exception):
    """Raised when token operations fail (missing file, refresh failure, etc.)."""

def refresh_access_token(refresh_token, client_id):
    data = urllib.parse.urlencode({
        "grant_type": "refresh_token",
        "refresh_token": refresh_token,
        "client_id": client_id,
    }).encode()
    req = urllib.request.Request(
        "https://login.eveonline.com/v2/oauth/token",
        data=data,
        headers={
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": USER_AGENT,
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", errors="replace")
        raise TokenError(f"Token refresh failed ({e.code}): {body}")
    except urllib.error.URLError as e:
        raise TokenError(f"Could not connect to EVE login server: {e.reason}")

def load_tokens_or_raise():
    tokens_file = get_tokens_file()
    if not os.path.exists(tokens_file):
        raise TokenError(f"Tokens file not found: {tokens_file}. Run auth_flow.py first to authenticate.")
    return load_tokens()

def validate_character_metadata(char_name, char_data):
    missing_fields = [
        field
        for field in ("refresh_token", "client_id")
        if not char_data.get(field)
    ]
    if missing_fields:
        fields = ", ".join(missing_fields)
        raise TokenError(
            f"Character '{char_name}' is missing required token metadata: {fields}. "
            f"Re-run auth_flow.py --char-name {char_name} to refresh the stored entry."
        )

def get_character_id(char_name):
    """Return the stored character_id for a character key."""
    chars = load_tokens_or_raise().get("characters", {})
    if char_name not in chars:
        raise TokenError(
            f"Character '{char_name}' not found. "
            f"Available: {', '.join(chars.keys()) or 'none'}. "
            f"Run auth_flow.py --char-name <name> to authenticate."
        )
    character_id = chars[char_name].get("character_id")
    if character_id is None:
        raise TokenError(
            f"Character '{char_name}' has no stored character_id. "
            f"Re-run auth_flow.py --char-name {char_name}."
        )
    return character_id

def resolve_access_token(char_name):
    """Refresh and return the full token response for a stored character.

    Importable entry point so other scripts can obtain a token in-process
    instead of passing it across a command line.
    """
    chars = load_tokens_or_raise().get("characters", {})
    if char_name not in chars:
        raise TokenError(
            f"Character '{char_name}' not found. "
            f"Available: {', '.join(chars.keys()) or 'none'}. "
            f"Run auth_flow.py --char-name <name> to authenticate."
        )

    # Lock the token file for the entire read-refresh-write cycle.
    # EVE SSO rotates refresh tokens on each use, so concurrent processes
    # must not read the same token before the new one is persisted.
    with token_file_lock():
        # Re-read under lock to get the freshest state
        tokens = load_tokens_or_raise()
        chars = tokens.get("characters", {})
        char = chars.get(char_name)
        if char is None:
            raise TokenError(
                f"Character '{char_name}' was removed before the lock could be acquired."
            )
        validate_character_metadata(char_name, char)

        token_data = refresh_access_token(char["refresh_token"], char["client_id"])
        if not token_data.get("access_token"):
            raise TokenError("Token refresh response did not include an access_token.")

        # Save updated refresh_token (EVE rotates it on each refresh)
        if "refresh_token" in token_data:
            chars[char_name]["refresh_token"] = token_data["refresh_token"]
            save_tokens_unlocked(tokens)

    return token_data

def main():
    parser = argparse.ArgumentParser(description="Get a fresh EVE ESI access token")
    parser.add_argument("--char", default="main",
                        help="Character key to use (default: main)")
    parser.add_argument("--json", action="store_true",
                        help="Output token response as JSON (refresh_token redacted)")
    parser.add_argument("--include-refresh-token", action="store_true",
                        help="With --json: include the long-lived refresh token in the "
                             "output. Only do this if you know where stdout ends up.")
    parser.add_argument("--char-id", action="store_true",
                        help="Print only the stored character ID (no token, no refresh)")
    parser.add_argument("--list", action="store_true",
                        help="List all stored characters")
    args = parser.parse_args()

    if args.list:
        chars = load_tokens_or_raise().get("characters", {})
        if not chars:
            print("No characters stored. Run auth_flow.py first.")
            return
        for key, c in chars.items():
            print(f"  {key}: {c.get('character_name')} (ID: {c.get('character_id')})")
        return

    if args.char_id:
        print(get_character_id(args.char))
        return

    token_data = resolve_access_token(args.char)

    if args.json:
        payload = dict(token_data)
        if "refresh_token" in payload and not args.include_refresh_token:
            # The refresh token is long-lived — never emit it unless asked.
            payload["refresh_token"] = "<redacted: pass --include-refresh-token to reveal>"
        elif args.include_refresh_token:
            print("WARNING: printing a long-lived refresh token to stdout. "
                  "Anyone who reads this output keeps account access until it is "
                  "revoked at https://community.eveonline.com/support/third-party/",
                  file=sys.stderr)
        print(json.dumps(payload, indent=2))
    else:
        print("Note: access token written to stdout (valid ~20 min). "
              "Prefer esi_query.py --char, which never prints it.", file=sys.stderr)
        print(token_data["access_token"])

if __name__ == "__main__":
    try:
        main()
    except TokenError as e:
        print(f"ERROR: {e}", file=sys.stderr)
        sys.exit(1)
```

## File: scripts/token_store.py
size: 2783
sha: b5bac07b2801c3e8beed275a96325b8913b57ee7
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/scripts/token_store.py

```text
#!/usr/bin/env python3
"""Shared helpers for safely reading and writing EVE token state."""

from __future__ import annotations

import json
import logging
import os
from contextlib import contextmanager

logger = logging.getLogger(__name__)

class TokenError(Exception):
    """Raised when a token store operation cannot be completed."""

if os.name == "nt":
    import msvcrt

    def _lock(file_obj):
        msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1)

    def _unlock(file_obj):
        msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1)
else:
    import fcntl

    def _lock(file_obj):
        fcntl.flock(file_obj, fcntl.LOCK_EX)

    def _unlock(file_obj):
        fcntl.flock(file_obj, fcntl.LOCK_UN)

def get_tokens_file() -> str:
    return os.path.join(
        os.environ.get("OPENCLAW_STATE_DIR", os.path.expanduser("~/.openclaw")),
        "eve-tokens.json",
    )

def _get_lock_file() -> str:
    return get_tokens_file() + ".lock"

def _ensure_state_dir():
    os.makedirs(os.path.dirname(get_tokens_file()), exist_ok=True)

@contextmanager
def token_file_lock():
    """Serialize all token file mutations across scripts/processes."""
    _ensure_state_dir()
    lock_file = open(_get_lock_file(), "a+")
    try:
        try:
            _lock(lock_file)
        except (IOError, OSError) as exc:
            lock_file.close()
            raise TokenError(
                "Could not acquire token file lock (timed out). "
                "Another process may be refreshing the token."
            ) from exc
        yield
    finally:
        _unlock(lock_file)
        lock_file.close()

def load_tokens() -> dict:
    """Load the token file if present, otherwise return an empty structure."""
    tokens_file = get_tokens_file()
    if os.path.exists(tokens_file):
        with open(tokens_file, encoding="utf-8") as handle:
            data = json.load(handle)
        if not isinstance(data, dict):
            logger.warning(
                "Token file contained unexpected type %s (expected dict); "
                "treating as empty. File: %s",
                type(data).__name__,
                tokens_file,
            )
            return {"characters": {}}
        return data
    return {"characters": {}}

def save_tokens_unlocked(data: dict):
    """Atomically persist token data. Caller must already hold the lock."""
    tokens_file = get_tokens_file()
    _ensure_state_dir()
    tmp_file = tokens_file + ".tmp"
    with open(tmp_file, "w", encoding="utf-8") as handle:
        json.dump(data, handle, indent=2)
    os.chmod(tmp_file, 0o600)
    os.replace(tmp_file, tokens_file)

def save_tokens(data: dict):
    """Lock and atomically persist token data."""
    with token_file_lock():
        save_tokens_unlocked(data)
```

## File: scripts/user_agent.py
size: 1243
sha: 43834efbc5d482ef52569585aa0f8412dff253d5
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/scripts/user_agent.py

```text
"""Shared User-Agent for every outbound call this skill makes.

CCP asks third parties to identify themselves on ESI requests and treats
anonymous traffic as grounds for throttling or a ban. Python's urllib would
otherwise announce itself as `Python-urllib/3.x`, which says nothing about who
is calling, so both the ESI client and the SSO scripts send this instead.

The format follows the guidance in
https://developers.eveonline.com/docs/services/esi/best-practices/ :
an app name with version, an optional contact, and a source URL marked `+`.
"""

import os

SKILL_VERSION = "1.3.3"
SOURCE_URL = "https://github.com/burnshall-ui/openclaw-eve-skill"

def build_user_agent() -> str:
    """Assemble the User-Agent string.

    A source URL is always sent. CCP strongly prefers a contact as well, so
    set EVE_ESI_CONTACT to an email address, `discord:name` or `eve:charname`
    to add one — it is left empty by default because the value belongs to
    whoever installed the skill, not to the skill.
    """
    contact = os.environ.get("EVE_ESI_CONTACT", "").strip()
    detail = f"{contact}; +{SOURCE_URL}" if contact else f"+{SOURCE_URL}"
    return f"OpenClaw-ESI-Skill/{SKILL_VERSION} ({detail})"

USER_AGENT = build_user_agent()
```

## File: scripts/validate_config.py
size: 16430
sha: ab1207029d23d3e9b92197f45517a0aec29e3cd1
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/scripts/validate_config.py

```text
#!/usr/bin/env python3
"""EVE Dashboard Config Validator.

Validates a config file against the schema and checks:
- JSON syntax
- Schema conformity (required fields, types, allowed values)
- Scope coverage (does the character have the scopes for its alert rules?)
- Env references ($ENV:VAR) — warns if variables are not set

Usage:
    python validate_config.py <config.json>
    python validate_config.py --example    # Show example config
    python validate_config.py --schema     # Show JSON schema

Requires: Python 3.8+ (uses only stdlib)
"""

import argparse
import json
import os
import re
import sys
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
SCHEMA_PATH = SCRIPT_DIR.parent / "config" / "schema.json"
EXAMPLE_PATH = SCRIPT_DIR.parent / "config" / "example-config.json"

# Which ESI scopes does each alert type require?
ALERT_SCOPE_MAP: dict[str, list[str]] = {
    "war_declared": ["esi-characters.read_notifications.v1"],
    "war_surrendered": ["esi-characters.read_notifications.v1"],
    "structure_fuel_low": ["esi-characters.read_notifications.v1"],
    "structure_under_attack": ["esi-characters.read_notifications.v1"],
    "skill_complete": ["esi-skills.read_skillqueue.v1"],
    "wallet_large_deposit": ["esi-wallet.read_character_wallet.v1"],
    "wallet_large_withdrawal": ["esi-wallet.read_character_wallet.v1"],
    "contract_expired": ["esi-contracts.read_character_contracts.v1"],
    "industry_job_complete": ["esi-industry.read_character_jobs.v1"],
    "pi_extractor_expired": ["esi-planets.manage_planets.v1"],
    "clone_jump_available": ["esi-characters.read_fatigue.v1"],
    "mail_received": ["esi-mail.read_mail.v1"],
    "killmail": ["esi-killmails.read_killmails.v1"],
}

# Which ESI scopes does each report type require?
REPORT_SCOPE_MAP: dict[str, list[str]] = {
    "net_worth": ["esi-wallet.read_character_wallet.v1", "esi-assets.read_assets.v1"],
    "skill_queue": ["esi-skills.read_skillqueue.v1"],
    "industry_jobs": ["esi-industry.read_character_jobs.v1"],
    "market_orders": ["esi-markets.read_character_orders.v1"],
    "wallet_summary": ["esi-wallet.read_character_wallet.v1"],
    "assets_summary": ["esi-assets.read_assets.v1"],
}

ENV_PATTERN = re.compile(r"^\$ENV:(.+)$")
INTERVAL_PATTERN = re.compile(r"^[0-9]+(s|m|h)$")
TREND_WINDOW_PATTERN = re.compile(r"^[0-9]+(m|h|d)$")

class ValidationResult:
    """Collects errors and warnings during validation."""

    def __init__(self):
        self.errors: list[str] = []
        self.warnings: list[str] = []

    def error(self, msg: str):
        self.errors.append(msg)

    def warn(self, msg: str):
        self.warnings.append(msg)

    @property
    def ok(self) -> bool:
        return len(self.errors) == 0

    def print_summary(self):
        if self.warnings:
            print(f"\n⚠ {len(self.warnings)} warning(s):", file=sys.stderr)
            for w in self.warnings:
                print(f"  - {w}", file=sys.stderr)

        if self.errors:
            print(f"\n✗ {len(self.errors)} error(s):", file=sys.stderr)
            for e in self.errors:
                print(f"  - {e}", file=sys.stderr)
        else:
            print("\n✓ Config is valid.", file=sys.stderr)

def load_schema() -> dict:
    """Load the bundled JSON schema."""
    return json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))

def format_path(path: str, key: str) -> str:
    """Join object paths while keeping root keys readable."""
    return f"{path}.{key}" if path else key

def validate_type(value, expected_type: str) -> bool:
    """Validate a JSON-schema primitive type."""
    if expected_type == "object":
        return isinstance(value, dict)
    if expected_type == "array":
        return isinstance(value, list)
    if expected_type == "string":
        return isinstance(value, str)
    if expected_type == "integer":
        return isinstance(value, int) and not isinstance(value, bool)
    if expected_type == "number":
        return isinstance(value, (int, float)) and not isinstance(value, bool)
    if expected_type == "boolean":
        return isinstance(value, bool)
    return True

def validate_against_schema(schema: dict, value, result: ValidationResult, path: str = ""):
    """Validate the config against the subset of JSON Schema used by this repo."""
    expected_type = schema.get("type")
    if expected_type and not validate_type(value, expected_type):
        current_path = path or "config"
        result.error(
            f"{current_path}: expected {expected_type}, got {type(value).__name__}"
        )
        return

    if "enum" in schema and value not in schema["enum"]:
        current_path = path or "config"
        allowed = ", ".join(repr(item) for item in schema["enum"])
        result.error(f"{current_path}: invalid value {value!r} (allowed: {allowed})")

    if isinstance(value, str) and "pattern" in schema:
        if not re.match(schema["pattern"], value):
            current_path = path or "config"
            result.error(
                f"{current_path}: value {value!r} does not match pattern {schema['pattern']!r}"
            )

    if isinstance(value, dict):
        properties = schema.get("properties", {})
        required_fields = schema.get("required", [])

        for field in required_fields:
            if field not in value:
                result.error(f"{format_path(path, field)}: required field is missing")

        if schema.get("additionalProperties", True) is False:
            for key in value:
                if key not in properties:
                    result.error(
                        f"{format_path(path, key)}: additional property is not allowed"
                    )

        for key, subschema in properties.items():
            if key in value:
                validate_against_schema(subschema, value[key], result, format_path(path, key))

    elif isinstance(value, list):
        min_items = schema.get("minItems")
        if min_items is not None and len(value) < min_items:
            current_path = path or "config"
            result.error(
                f"{current_path}: expected at least {min_items} item(s), got {len(value)}"
            )

        item_schema = schema.get("items")
        if item_schema:
            for index, item in enumerate(value):
                validate_against_schema(item_schema, item, result, f"{path}[{index}]")

def resolve_env_value(value: str) -> tuple[str | None, bool]:
    """Resolve $ENV:VAR references. Returns (resolved_value, is_env_ref)."""
    if not isinstance(value, str):
        return value, False

    match = ENV_PATTERN.match(value)
    if not match:
        return value, False

    var_name = match.group(1)
    env_val = os.environ.get(var_name)
    return env_val, True

def check_env_refs(config: dict, result: ValidationResult, path: str = ""):
    """Recursively scan config for $ENV: references and check if they are set."""
    if isinstance(config, dict):
        for key, value in config.items():
            current_path = f"{path}.{key}" if path else key
            if isinstance(value, str):
                resolved, is_env = resolve_env_value(value)
                if is_env and resolved is None:
                    var_name = ENV_PATTERN.match(value).group(1)
                    result.warn(f"{current_path}: env variable '{var_name}' is not set")
            elif isinstance(value, (dict, list)):
                check_env_refs(value, result, current_path)
    elif isinstance(config, list):
        for i, item in enumerate(config):
            check_env_refs(item, result, f"{path}[{i}]")

def validate_required_fields(config: dict, result: ValidationResult):
    """Check that all required fields are present."""
    # Top-level
    if "schema_version" not in config:
        result.error("Required field 'schema_version' is missing")
    elif config["schema_version"] != "1.0":
        result.error(f"Unknown schema_version: '{config['schema_version']}' (expected: '1.0')")

    if "notification_channels" not in config:
        result.error("Required field 'notification_channels' is missing")
    else:
        channels = config["notification_channels"]
        if not isinstance(channels, dict) or len(channels) == 0:
            result.error("'notification_channels' must define at least one channel")

    if "characters" not in config:
        result.error("Required field 'characters' is missing")
    elif not isinstance(config["characters"], list) or len(config["characters"]) == 0:
        result.error("'characters' must contain at least one character")
    else:
        for i, char in enumerate(config["characters"]):
            prefix = f"characters[{i}]"
            if "scopes" in char and (not isinstance(char["scopes"], list) or len(char["scopes"]) == 0):
                result.warn(f"{prefix}: 'scopes' is empty — no authenticated endpoint will work")

def validate_intervals(config: dict, result: ValidationResult):
    """Check that interval strings have the correct format."""
    # alerts.check_interval
    alerts = config.get("alerts", {})
    if "check_interval" in alerts:
        if not INTERVAL_PATTERN.match(alerts["check_interval"]):
            result.error(f"alerts.check_interval: invalid format '{alerts['check_interval']}' (expected e.g. '5m', '1h')")

    # alerts.rules[].cooldown
    for i, rule in enumerate(alerts.get("rules", [])):
        if "cooldown" in rule and not INTERVAL_PATTERN.match(rule["cooldown"]):
            result.error(f"alerts.rules[{i}].cooldown: invalid format '{rule['cooldown']}'")

    # market.check_interval
    market = config.get("market", {})
    if "check_interval" in market:
        if not INTERVAL_PATTERN.match(market["check_interval"]):
            result.error(f"market.check_interval: invalid format '{market['check_interval']}'")

    # market.items[].cooldown, trend_alert.time_window
    for i, item in enumerate(market.get("items", [])):
        if "cooldown" in item and not INTERVAL_PATTERN.match(item["cooldown"]):
            result.error(f"market.items[{i}].cooldown: invalid format '{item['cooldown']}'")
        trend = item.get("trend_alert", {})
        if "time_window" in trend and not TREND_WINDOW_PATTERN.match(trend["time_window"]):
            result.error(f"market.items[{i}].trend_alert.time_window: invalid format '{trend['time_window']}'")

def validate_alert_types(config: dict, result: ValidationResult):
    """Check that alert types are valid."""
    valid_types = set(ALERT_SCOPE_MAP.keys())
    for i, rule in enumerate(config.get("alerts", {}).get("rules", [])):
        alert_type = rule.get("type")
        if alert_type and alert_type not in valid_types:
            result.error(f"alerts.rules[{i}].type: unknown alert type '{alert_type}'")

        severity = rule.get("severity")
        if severity and severity not in ("info", "warning", "critical"):
            result.error(f"alerts.rules[{i}].severity: invalid '{severity}' (allowed: info, warning, critical)")

def validate_report_templates(config: dict, result: ValidationResult):
    """Check that report templates are valid."""
    valid_templates = set(REPORT_SCOPE_MAP.keys())
    for i, tpl in enumerate(config.get("reports", {}).get("templates", [])):
        name = tpl.get("name")
        if name and name not in valid_templates:
            result.error(f"reports.templates[{i}].name: unknown template '{name}'")

        fmt = tpl.get("format")
        if fmt and fmt not in ("short", "detailed"):
            result.error(f"reports.templates[{i}].format: invalid '{fmt}' (allowed: short, detailed)")

def validate_scope_coverage(config: dict, result: ValidationResult):
    """Check that characters have the scopes required by their alerts and reports."""
    characters = config.get("characters", [])
    if not characters:
        return

    # Check each character
    for char in characters:
        if not char.get("enabled", True):
            continue

        char_scopes = set(char.get("scopes", []))
        char_name = char.get("name", f"ID {char.get('id', '?')}")
        char_id = char.get("id")
        needed_scopes: dict[str, list[str]] = {}

        for rule in config.get("alerts", {}).get("rules", []):
            filter_ids = set(rule.get("character_filter", []))
            if filter_ids and char_id not in filter_ids:
                continue
            alert_type = rule.get("type", "")
            for scope in ALERT_SCOPE_MAP.get(alert_type, []):
                needed_scopes.setdefault(scope, []).append(f"alert:{alert_type}")

        for tpl in config.get("reports", {}).get("templates", []):
            filter_ids = set(tpl.get("character_filter", []))
            if filter_ids and char_id not in filter_ids:
                continue
            tpl_name = tpl.get("name", "")
            for scope in REPORT_SCOPE_MAP.get(tpl_name, []):
                needed_scopes.setdefault(scope, []).append(f"report:{tpl_name}")

        for scope, reasons in needed_scopes.items():
            if scope not in char_scopes:
                reasons_str = ", ".join(sorted(set(reasons)))
                result.warn(
                    f"Character '{char_name}': scope '{scope}' is missing "
                    f"(required for: {reasons_str})"
                )

def validate_channel_refs(config: dict, result: ValidationResult):
    """Check that referenced channels are defined in notification_channels."""
    defined = set(config.get("notification_channels", {}).keys())

    # alerts.channels
    for ch in config.get("alerts", {}).get("channels", []):
        if ch not in defined:
            result.error(f"alerts.channels: channel '{ch}' not defined in notification_channels")

    # reports.channels
    for ch in config.get("reports", {}).get("channels", []):
        if ch not in defined:
            result.error(f"reports.channels: channel '{ch}' not defined in notification_channels")

    # market.channels
    for ch in config.get("market", {}).get("channels", []):
        if ch not in defined:
            result.error(f"market.channels: channel '{ch}' not defined in notification_channels")

def validate_config(config: dict) -> ValidationResult:
    """Run all validations and return the result."""
    result = ValidationResult()

    validate_against_schema(load_schema(), config, result)
    validate_required_fields(config, result)
    validate_intervals(config, result)
    validate_alert_types(config, result)
    validate_report_templates(config, result)
    validate_scope_coverage(config, result)
    validate_channel_refs(config, result)
    check_env_refs(config, result)

    return result

def main():
    parser = argparse.ArgumentParser(description="EVE Dashboard Config Validator")
    parser.add_argument("config_file", nargs="?", help="Path to config JSON file")
    parser.add_argument("--example", action="store_true", help="Show example config")
    parser.add_argument("--schema", action="store_true", help="Show JSON schema")
    args = parser.parse_args()

    if args.example:
        if not EXAMPLE_PATH.exists():
            print(f"Example config not found: {EXAMPLE_PATH}", file=sys.stderr)
            sys.exit(1)
        print(EXAMPLE_PATH.read_text(encoding="utf-8"))
        return

    if args.schema:
        if not SCHEMA_PATH.exists():
            print(f"Schema not found: {SCHEMA_PATH}", file=sys.stderr)
            sys.exit(1)
        print(SCHEMA_PATH.read_text(encoding="utf-8"))
        return

    if not args.config_file:
        parser.print_help()
        sys.exit(1)

    config_path = Path(args.config_file)
    if not config_path.exists():
        print(f"Config file not found: {config_path}", file=sys.stderr)
        sys.exit(1)

    # Load JSON
    try:
        config = json.loads(config_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        print(f"JSON syntax error in {config_path}:", file=sys.stderr)
        print(f"  Line {e.lineno}, column {e.colno}: {e.msg}", file=sys.stderr)
        sys.exit(1)

    if not isinstance(config, dict):
        print("Config must be a JSON object (not array/string/etc.)", file=sys.stderr)
        sys.exit(1)

    # Validate
    print(f"Validating: {config_path}", file=sys.stderr)
    result = validate_config(config)
    result.print_summary()

    sys.exit(0 if result.ok else 1)

if __name__ == "__main__":
    main()
```

## File: references/authentication.md
size: 6041
sha: cc14ca9ae994b180cada65c5c981a57c22b6fcd7
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/references/authentication.md

````text
# EVE SSO OAuth2 Authentication

EVE ESI uses OAuth 2.0 Authorization Code flow via EVE SSO (Single Sign-On).

Base SSO URL: `https://login.eveonline.com`
Endpoint discovery: <https://login.eveonline.com/.well-known/oauth-authorization-server>

> **Everything on this page is a secret.** Authorization codes, access tokens,
> refresh tokens, client IDs and PKCE verifiers are all bearer credentials —
> whoever holds one can act as the character. The refresh token is the one that
> matters most: access tokens expire in ~20 minutes, refresh tokens do not
> expire on their own and grant continued access until revoked at
> <https://community.eveonline.com/support/third-party/>.
>
> Do not paste them into shell history, log files, CI output, config files under
> version control, or agent chat transcripts. In normal use you never handle
> them yourself: `auth_flow.py` writes them to `~/.openclaw/eve-tokens.json`
> (chmod 600) and `esi_query.py --char <name>` resolves them in-process without
> ever printing one. The examples below are the raw protocol, shown so the flow
> is auditable — not the recommended way to work with it.

## Prerequisites

1. Register an application at <https://developers.eveonline.com/applications>
2. Note your **Client ID** and **Secret Key**
3. Set the **Callback URL** to exactly `http://localhost:8080/callback` — this is
   what `auth_flow.py` sends, and SSO matches redirect URLs as literal strings.
   The developer portal accepts the `http` scheme *only* for the host
   `localhost`; an IP address such as `127.0.0.1` is rejected when you save the
   application. Using a different `--port`? Register that port's URL instead.
4. Select required **Scopes** for the endpoints you need

## Authorization Code Flow

### Step 1: Redirect user to SSO

```
https://login.eveonline.com/v2/oauth/authorize/?response_type=code&redirect_uri=<CALLBACK_URL>&client_id=<CLIENT_ID>&scope=<SCOPES>&state=<RANDOM_STATE>
```

- `scope`: space-separated list (e.g. `esi-wallet.read_character_wallet.v1 esi-assets.read_assets.v1`)
- `state`: random string to prevent CSRF

### Step 2: Exchange authorization code for tokens

```bash
curl -X POST https://login.eveonline.com/v2/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=<AUTH_CODE>" \
  -d "client_id=<CLIENT_ID>" \
  -d "code_verifier=<CODE_VERIFIER>"
```

Response:

```json
{
  "access_token": "eyJ...",
  "expires_in": 1199,
  "token_type": "Bearer",
  "refresh_token": "abc123..."
}
```

### Step 3: Refresh expired tokens

Access tokens expire after ~20 minutes. Refresh with:

```bash
curl -X POST https://login.eveonline.com/v2/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=<REFRESH_TOKEN>" \
  -d "client_id=<CLIENT_ID>"
```

### Step 4: Verify token and get character ID

```bash
curl -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "User-Agent: <your app>/<version> (+<your repo>)" \
  https://login.eveonline.com/v2/oauth/verify
```

Response includes `CharacterID`, `CharacterName`, `Scopes`.

The access token is also a JWT, so the same claims can be read without a round
trip: `sub` holds `CHARACTER:EVE:<character-id>`, `name` the character name and
`scp` the granted scopes. To verify a token you did not fetch yourself, check
its signature against the JWKS URL published in the SSO metadata document, and
confirm `iss` is `login.eveonline.com` and `aud` contains your client ID.

## Using tokens with ESI

Pass the access token as a Bearer header:

```bash
curl -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "X-Compatibility-Date: 2026-08-04" \
  -H "User-Agent: <your app>/<version> (+<your repo>)" \
  "https://esi.evetech.net/characters/<CHARACTER_ID>/wallet/"
```

Note there is no version segment in the path: ESI selects behaviour from the
`X-Compatibility-Date` header. Prefer `esi_query.py --char <name>`, which sets
both headers and keeps the token out of your command line entirely.

## PKCE (Proof Key for Code Exchange)

EVE SSO supports PKCE for public clients (no secret key). Generate a `code_verifier` (random 43-128 char string) and derive `code_challenge` via SHA-256:

```python
import hashlib, base64, secrets
code_verifier = secrets.token_urlsafe(64)
code_challenge = base64.urlsafe_b64encode(
    hashlib.sha256(code_verifier.encode()).digest()
).rstrip(b"=").decode()
```

Add `&code_challenge=<CHALLENGE>&code_challenge_method=S256` to the authorize URL. Include `code_verifier` in the token exchange.

## Required Scopes by Category

| Category | Scope |
|----------|-------|
| Wallet | `esi-wallet.read_character_wallet.v1` |
| Assets | `esi-assets.read_assets.v1` |
| Skills | `esi-skills.read_skills.v1`, `esi-skills.read_skillqueue.v1` |
| Clones | `esi-clones.read_clones.v1`, `esi-clones.read_implants.v1` |
| Location | `esi-location.read_location.v1`, `esi-location.read_ship_type.v1`, `esi-location.read_online.v1` |
| Contacts | `esi-characters.read_contacts.v1` |
| Contracts | `esi-contracts.read_character_contracts.v1` |
| Fittings | `esi-fittings.read_fittings.v1` |
| Mail | `esi-mail.read_mail.v1` |
| Calendar | `esi-calendar.read_calendar_events.v1` |
| Industry | `esi-industry.read_character_jobs.v1` |
| Market Orders | `esi-markets.read_character_orders.v1` |
| Killmails | `esi-killmails.read_killmails.v1` |
| Blueprints | `esi-characters.read_blueprints.v1` |
| Notifications | `esi-characters.read_notifications.v1` |
| Bookmarks | `esi-bookmarks.read_character_bookmarks.v1` |
| Loyalty | `esi-characters.read_loyalty.v1` |
| Mining | `esi-industry.read_character_mining.v1` |
| Roles | `esi-characters.read_corporation_roles.v1` |
| Standings | `esi-characters.read_standings.v1` |
| Fatigue | `esi-characters.read_fatigue.v1` |
| Medals | `esi-characters.read_medals.v1` |
| Titles | `esi-characters.read_titles.v1` |
| Agent Research | `esi-characters.read_agents_research.v1` |
| FW Stats | `esi-characters.read_fw_stats.v1` |
````

## File: references/endpoints.md
size: 13891
sha: 308a5f3593f1b056b30860d3fbc93f36998de3f0
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/references/endpoints.md

```text
# EVE ESI Character Endpoints Reference

Base URL: `https://esi.evetech.net` — no version segment. Send
`X-Compatibility-Date: 2026-08-04` on every request; a request without it is
served the oldest behaviour ESI still supports, not the newest. The old
`/latest/` and `/v5/` prefixes are deprecated. See
<https://esi.evetech.net/meta/compatibility-dates> for valid dates.

All authenticated endpoints require `Authorization: Bearer <TOKEN>` header. Replace `{character_id}` with the numeric character ID from SSO verify.

Also send a `User-Agent` that names the application and a way to reach its
author — CCP uses it to identify traffic and may throttle callers it cannot
place.

## Before you use this list: data sensitivity

Many endpoints below return data that the character owner would consider private.
Treat them accordingly.

| Sensitivity | Endpoints | Why it matters |
|---|---|---|
| **High** | Wallet balance, journal and transactions; mail headers and bodies; contacts; assets; contracts | Financial history and private correspondence. Mail in particular may contain third parties who never consented to being read. |
| **Medium** | Current location and online status; clones and implants; planetary installations; industry jobs; market orders | Reveals activity patterns and holdings; useful to an adversary in-game. |
| **Low** | Public character info, corporation history, portraits, skill points | Visible to anyone in game anyway. |

Rules of thumb when building on this reference:

- **Request the narrowest scope set that answers the question.** A skill that only
  reports skill points does not need `esi-wallet.read_character_wallet.v1`.
  Scopes are granted once at login and persist until the token is revoked.
- **Fetch on demand, do not stockpile.** Caching wallet or mail contents to disk
  turns a short-lived query into a lasting data store you then have to protect.
- **Be explicit when forwarding.** Sending balances or mail into Telegram, Discord
  or a dashboard moves private data into a third-party system in clear text.
  Say so before doing it, not afterwards.
- **Owner-visible does not mean agent-visible.** The user authorised *the skill*
  to read this data; that is not blanket permission to quote it into a shared
  channel or a log file.

Access can be withdrawn at any time at
<https://community.eveonline.com/support/third-party/>.

## Table of Contents

- [Character Info](#character-info)
- [Wallet](#wallet)
- [Assets](#assets)
- [Skills](#skills)
- [Clones and Implants](#clones-and-implants)
- [Location](#location)
- [Contacts](#contacts)
- [Contracts](#contracts)
- [Calendar](#calendar)
- [Fittings](#fittings)
- [Industry](#industry)
- [Killmails](#killmails)
- [Mail](#mail)
- [Market Orders](#market-orders)
- [Mining](#mining)
- [Notifications](#notifications)
- [Loyalty Points](#loyalty-points)
- [Planets (PI)](#planets-pi)
- [Blueprints](#blueprints)
- [Roles and Titles](#roles-and-titles)
- [Standings](#standings)
- [Bookmarks](#bookmarks)
- [Medals](#medals)
- [Agent Research](#agent-research)
- [Fatigue](#fatigue)
- [Faction Warfare](#faction-warfare)
- [Corporation History](#corporation-history)
- [Portrait](#portrait)
- [Search](#search)
- [Fleet](#fleet)

---

## Character Info

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/` | -- | Public character info (name, corp, birthday, etc.) |
| GET | `/characters/{character_id}/online/` | `esi-location.read_online.v1` | Online status, last login/logout |
| POST | `/characters/affiliation/` | -- | Bulk lookup corp/alliance/faction for character IDs |

## Wallet

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/wallet/` | `esi-wallet.read_character_wallet.v1` | ISK balance |
| GET | `/characters/{character_id}/wallet/journal/` | `esi-wallet.read_character_wallet.v1` | Wallet journal (paginated) |
| GET | `/characters/{character_id}/wallet/transactions/` | `esi-wallet.read_character_wallet.v1` | Wallet transactions |

## Assets

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/assets/` | `esi-assets.read_assets.v1` | All assets (paginated) |
| POST | `/characters/{character_id}/assets/locations/` | `esi-assets.read_assets.v1` | Locations for specific item IDs |
| POST | `/characters/{character_id}/assets/names/` | `esi-assets.read_assets.v1` | Names for specific item IDs |

## Skills

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/skills/` | `esi-skills.read_skills.v1` | All trained skills + total SP |
| GET | `/characters/{character_id}/skillqueue/` | `esi-skills.read_skillqueue.v1` | Current skill queue |
| GET | `/characters/{character_id}/attributes/` | `esi-skills.read_skills.v1` | Character attributes (int, mem, etc.) |

## Clones and Implants

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/clones/` | `esi-clones.read_clones.v1` | Jump clones and home location |
| GET | `/characters/{character_id}/implants/` | `esi-clones.read_implants.v1` | Active implant type IDs |

## Location

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/location/` | `esi-location.read_location.v1` | Current solar system, station/structure |
| GET | `/characters/{character_id}/ship/` | `esi-location.read_ship_type.v1` | Current ship type and name |

## Contacts

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/contacts/` | `esi-characters.read_contacts.v1` | Contact list |
| POST | `/characters/{character_id}/contacts/` | `esi-characters.write_contacts.v1` | Add contacts |
| PUT | `/characters/{character_id}/contacts/` | `esi-characters.write_contacts.v1` | Edit contacts |
| DELETE | `/characters/{character_id}/contacts/` | `esi-characters.write_contacts.v1` | Delete contacts |
| GET | `/characters/{character_id}/contacts/labels/` | `esi-characters.read_contacts.v1` | Contact labels |

## Contracts

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/contracts/` | `esi-contracts.read_character_contracts.v1` | All contracts (paginated) |
| GET | `/characters/{character_id}/contracts/{contract_id}/bids/` | `esi-contracts.read_character_contracts.v1` | Bids on a contract |
| GET | `/characters/{character_id}/contracts/{contract_id}/items/` | `esi-contracts.read_character_contracts.v1` | Items in a contract |

## Calendar

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/calendar/` | `esi-calendar.read_calendar_events.v1` | Upcoming events (50 max) |
| GET | `/characters/{character_id}/calendar/{event_id}/` | `esi-calendar.read_calendar_events.v1` | Event details |
| GET | `/characters/{character_id}/calendar/{event_id}/attendees/` | `esi-calendar.read_calendar_events.v1` | Event attendees |
| PUT | `/characters/{character_id}/calendar/{event_id}/` | `esi-calendar.respond_calendar_events.v1` | Respond to event |

## Fittings

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/fittings/` | `esi-fittings.read_fittings.v1` | Saved fittings |
| POST | `/characters/{character_id}/fittings/` | `esi-fittings.write_fittings.v1` | Create a fitting |
| DELETE | `/characters/{character_id}/fittings/{fitting_id}/` | `esi-fittings.write_fittings.v1` | Delete a fitting |

## Industry

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/industry/jobs/` | `esi-industry.read_character_jobs.v1` | Industry jobs (manufacturing, research, etc.) |

## Killmails

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/killmails/recent/` | `esi-killmails.read_killmails.v1` | Recent killmail IDs + hashes |
| GET | `/killmails/{killmail_id}/{killmail_hash}/` | -- | Full killmail details (public) |

## Mail

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/mail/` | `esi-mail.read_mail.v1` | Mail headers (paginated) |
| GET | `/characters/{character_id}/mail/{mail_id}/` | `esi-mail.read_mail.v1` | Single mail body |
| POST | `/characters/{character_id}/mail/` | `esi-mail.send_mail.v1` | Send a mail |
| PUT | `/characters/{character_id}/mail/{mail_id}/` | `esi-mail.organize_mail.v1` | Update labels / mark read |
| DELETE | `/characters/{character_id}/mail/{mail_id}/` | `esi-mail.organize_mail.v1` | Delete a mail |
| GET | `/characters/{character_id}/mail/labels/` | `esi-mail.read_mail.v1` | Mail labels + unread counts |
| POST | `/characters/{character_id}/mail/labels/` | `esi-mail.organize_mail.v1` | Create mail label |
| GET | `/characters/{character_id}/mail/lists/` | `esi-mail.read_mail.v1` | Mailing lists |

## Market Orders

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/orders/` | `esi-markets.read_character_orders.v1` | Active market orders |
| GET | `/characters/{character_id}/orders/history/` | `esi-markets.read_character_orders.v1` | Expired/cancelled orders (paginated) |

## Mining

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/mining/` | `esi-industry.read_character_mining.v1` | Mining ledger (last 30 days) |

## Notifications

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/notifications/` | `esi-characters.read_notifications.v1` | All notifications |
| GET | `/characters/{character_id}/notifications/contacts/` | `esi-characters.read_notifications.v1` | Contact notifications |

## Loyalty Points

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/loyalty/points/` | `esi-characters.read_loyalty.v1` | LP balances per corp |

## Planets (PI)

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/planets/` | `esi-planets.manage_planets.v1` | List of colonies |
| GET | `/characters/{character_id}/planets/{planet_id}/` | `esi-planets.manage_planets.v1` | Colony layout and extractors |

## Blueprints

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/blueprints/` | `esi-characters.read_blueprints.v1` | All blueprints (paginated) |

## Roles and Titles

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/roles/` | `esi-characters.read_corporation_roles.v1` | Corporation roles |
| GET | `/characters/{character_id}/titles/` | `esi-characters.read_titles.v1` | Corporation titles |

## Standings

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/standings/` | `esi-characters.read_standings.v1` | NPC standings |

## Bookmarks

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/bookmarks/` | `esi-bookmarks.read_character_bookmarks.v1` | All bookmarks (paginated) |
| GET | `/characters/{character_id}/bookmarks/folders/` | `esi-bookmarks.read_character_bookmarks.v1` | Bookmark folders |

## Medals

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/medals/` | `esi-characters.read_medals.v1` | Awarded medals |

## Agent Research

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/agents_research/` | `esi-characters.read_agents_research.v1` | Research agents and points |

## Fatigue

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/fatigue/` | `esi-characters.read_fatigue.v1` | Jump fatigue expiry timestamps |

## Faction Warfare

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/fw/stats/` | `esi-characters.read_fw_stats.v1` | FW kill/VP stats |

## Corporation History

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/corporationhistory/` | -- | Public employment history |

## Portrait

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/portrait/` | -- | Portrait URLs (64/128/256/512px) |

## Search

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/search/` | `esi-search.search_structures.v1` | Authenticated search (includes structures) |

## Fleet

| Method | Path | Scope | Description |
|--------|------|-------|-------------|
| GET | `/characters/{character_id}/fleet/` | `esi-fleets.read_fleet.v1` | Current fleet info |

---

## Pagination

Paginated endpoints return `X-Pages` header. Append `?page=N` (1-based). Always check `X-Pages` to determine total pages.

## Caching

Every response includes `Expires` and `Last-Modified` headers. Do not request again before `Expires`. Use `If-None-Match` with the `ETag` header for conditional requests (returns 304 if unchanged).

## Error Handling

- `403`: Missing scope or wrong character
- `404`: Resource not found
- `420`: Error rate limited (back off and retry)
- `502/503/504`: Upstream server issue (retry with backoff)
- Check `X-ESI-Error-Limit-Remain` and `X-ESI-Error-Limit-Reset` headers
```

## File: .github/workflows/ci.yml
size: 1342
sha: 1e0244392013bacf1d4c28b65a0f6c6df5cee8c2
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/.github/workflows/ci.yml

```text
name: CI

on:
  push:
    branches: [master]
  pull_request:

jobs:
  test:
    name: Tests (Python ${{ matrix.python-version }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        # Everything here is standard library only, so the version range is the
        # only thing worth spending matrix time on. 3.10 is the real floor: the
        # scripts annotate with PEP 604 unions (`str | None`) and do not import
        # `annotations` from __future__, so they fail to import on 3.9.
        python-version: ["3.10", "3.11", "3.12", "3.13"]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
      - name: Regression tests
        run: python tests/test_regressions.py -v
      - name: Byte-compile every script
        run: python -m compileall -q scripts tests

  config:
    name: Config schema
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      # The example config is what users copy. If it stops validating against
      # the schema, everyone's first run fails.
      - name: Validate the shipped example config
        run: python scripts/validate_config.py config/example-config.json
```

## File: .gitignore
size: 279
sha: df46dadea7bd2f7fd5963d41759251b14d2f7a86
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/.gitignore

```text
# Tokens and secrets — NEVER commit these
eve-tokens.json
*tokens*.json
*credentials*
*.secret
.env

# Dashboard config (may contain token references)
eve-dashboard-config.json

# Temp files from atomic writes
*.tmp

# Python
__pycache__/
*.pyc
*.pyo

# OS
.DS_Store
Thumbs.db
```

## File: .mailmap
size: 898
sha: a972c5cea8f574c946a71eceec5a072543092dab
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/.mailmap

```text
# Canonical commit identity for this repository.
#
# Commits were made from several machines with differing git configs. This maps
# every stray name/address onto one identity so `git log`, `git shortlog` and
# `git blame` show a single author.
#
# Note: this is presentation only. It does not rewrite history, and GitHub's web
# UI ignores .mailmap — the original addresses remain in the commit objects.
# Preventing new ones is a matter of `git config` on each machine.

burnshall-ui <burnshall-ui@users.noreply.github.com> <burn.shall@googlemail.com>
burnshall-ui <burnshall-ui@users.noreply.github.com> <burnshall-ui@github.com>
burnshall-ui <burnshall-ui@users.noreply.github.com> <tomasz@tomaszs-air.speedport.ip>
burnshall-ui <burnshall-ui@users.noreply.github.com> <t.sporys@t-online.de>
burnshall-ui <burnshall-ui@users.noreply.github.com> Thomas <burnshall-ui@users.noreply.github.com>
```

## File: config/esi_endpoints.json
size: 2106
sha: f8a0b1a3d5d96cf9a0924fe3df8f36bd5e477095
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/config/esi_endpoints.json

```text
{
  "pi_planets": {
    "path": "/characters/{character_id}/planets/",
    "method": "GET",
    "auth": true,
    "scope": "esi-planets.manage_planets.v1",
    "description": "Liste aller PI-Planeten eines Characters"
  },
  "pi_planet_detail": {
    "path": "/characters/{character_id}/planets/{planet_id}/",
    "method": "GET",
    "auth": true,
    "scope": "esi-planets.manage_planets.v1",
    "description": "Extraktoren, Factories, Links und Routes eines Planeten"
  },
  "universe_planet": {
    "path": "/universe/planets/{planet_id}/",
    "method": "GET",
    "auth": false,
    "description": "Planet-Metadaten (Name, Typ, System)"
  },
  "market_prices": {
    "path": "/markets/prices/",
    "method": "GET",
    "auth": false,
    "description": "Alle adjusted/average Preise (global)"
  },
  "market_orders": {
    "path": "/markets/10000002/orders/",
    "method": "GET",
    "auth": false,
    "params": [
      "type_id",
      "order_type"
    ],
    "description": "Jita Buy/Sell Orders fuer ein bestimmtes Item"
  },
  "system_kills": {
    "path": "/universe/system_kills/",
    "method": "GET",
    "auth": false,
    "description": "Ship/Pod/NPC Kills pro System (letzte Stunde)"
  },
  "system_jumps": {
    "path": "/universe/system_jumps/",
    "method": "GET",
    "auth": false,
    "description": "Jump-Traffic pro System (letzte Stunde)"
  },
  "route": {
    "path": "/route/{origin}/{destination}/",
    "method": "GET",
    "auth": false,
    "params": ["flag"],
    "description": "Routenplanung (flags: shortest, secure, insecure)"
  },
  "system_info": {
    "path": "/universe/systems/{system_id}/",
    "method": "GET",
    "auth": false,
    "description": "System-Name, Security-Status, Constellation, Star"
  },
  "incursions": {
    "path": "/incursions/",
    "method": "GET",
    "auth": false,
    "description": "Aktive NPC-Incursions (Constellation, Staging System, State)"
  },
  "fw_systems": {
    "path": "/fw/systems/",
    "method": "GET",
    "auth": false,
    "description": "Faction-Warfare umkaempfte Systeme mit Ownership/Contested-Level"
  }
}
```

## File: config/example-config.json
size: 3581
sha: 3bb16bc72642e28d472c7a211864f183ef918b35
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/config/example-config.json

```text
{
  "schema_version": "1.0",

  "notification_channels": {
    "telegram": {
      "bot_token": "$ENV:TELEGRAM_BOT_TOKEN",
      "chat_id": "$ENV:TELEGRAM_CHAT_ID"
    }
  },

  "characters": [
    {
      "id": 2114794365,
      "name": "Main Character",
      "token": "$ENV:EVE_TOKEN_MAIN",
      "refresh_token": "$ENV:EVE_REFRESH_MAIN",
      "client_id": "$ENV:EVE_CLIENT_ID",
      "scopes": [
        "esi-wallet.read_character_wallet.v1",
        "esi-skills.read_skills.v1",
        "esi-skills.read_skillqueue.v1",
        "esi-assets.read_assets.v1",
        "esi-clones.read_clones.v1",
        "esi-clones.read_implants.v1",
        "esi-location.read_location.v1",
        "esi-location.read_ship_type.v1",
        "esi-location.read_online.v1",
        "esi-characters.read_notifications.v1",
        "esi-industry.read_character_jobs.v1",
        "esi-markets.read_character_orders.v1",
        "esi-contracts.read_character_contracts.v1",
        "esi-killmails.read_killmails.v1",
        "esi-planets.manage_planets.v1",
        "esi-characters.read_fatigue.v1",
        "esi-mail.read_mail.v1"
      ],
      "corporation": {
        "id": 98000001,
        "name": "My Corp"
      },
      "enabled": true
    }
  ],

  "alerts": {
    "enabled": true,
    "check_interval": "5m",
    "channels": ["telegram"],
    "rules": [
      {
        "type": "war_declared",
        "severity": "critical"
      },
      {
        "type": "structure_under_attack",
        "severity": "critical"
      },
      {
        "type": "structure_fuel_low",
        "severity": "warning",
        "threshold": 24
      },
      {
        "type": "skill_complete",
        "severity": "info",
        "cooldown": "1h"
      },
      {
        "type": "wallet_large_deposit",
        "severity": "info",
        "threshold": 1000000000
      },
      {
        "type": "industry_job_complete",
        "severity": "info",
        "cooldown": "30m"
      },
      {
        "type": "pi_extractor_expired",
        "severity": "warning"
      },
      {
        "type": "killmail",
        "severity": "info"
      },
      {
        "type": "contract_expired",
        "severity": "warning",
        "cooldown": "2h"
      }
    ]
  },

  "reports": {
    "enabled": true,
    "schedule": "0 9,21 * * *",
    "timezone": "Europe/Berlin",
    "channels": ["telegram"],
    "templates": [
      {
        "name": "net_worth",
        "format": "short"
      },
      {
        "name": "skill_queue",
        "format": "detailed"
      },
      {
        "name": "wallet_summary",
        "format": "short"
      },
      {
        "name": "assets_summary",
        "format": "short"
      }
    ]
  },

  "market": {
    "enabled": true,
    "check_interval": "30m",
    "channels": ["telegram"],
    "items": [
      {
        "type_id": 44992,
        "name": "PLEX",
        "region_id": 10000002,
        "region_name": "The Forge",
        "alert_above": 4500000,
        "alert_below": 3500000,
        "trend_alert": {
          "change_percent": 10,
          "time_window": "1h"
        },
        "cooldown": "1h"
      },
      {
        "type_id": 34,
        "name": "Tritanium",
        "region_id": 10000002,
        "region_name": "The Forge",
        "trend_alert": {
          "change_percent": 15,
          "time_window": "6h"
        }
      },
      {
        "type_id": 16274,
        "name": "Skill Injector",
        "region_id": 10000002,
        "region_name": "The Forge",
        "alert_below": 800000000,
        "cooldown": "2h"
      }
    ]
  }
}
```

## File: config/schema.json
size: 10982
sha: 36c3d4110fc6e48bea76f57f7eaaa0ad7173b172
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/config/schema.json

```text
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "EVE Dashboard Config",
  "description": "Modular config schema for the EVE Command Center. Each user configures which alerts, reports, and market trackers they need.",
  "type": "object",
  "properties": {

    "schema_version": {
      "type": "string",
      "description": "Schema version for future migrations",
      "default": "1.0",
      "enum": ["1.0"]
    },

    "notification_channels": {
      "type": "object",
      "description": "Connection details for notification channels. Values can be literal or $ENV:VARIABLE_NAME references.",
      "properties": {
        "telegram": {
          "type": "object",
          "properties": {
            "bot_token": {
              "type": "string",
              "description": "Telegram Bot Token (e.g. '123456:ABC-DEF...' or '$ENV:TELEGRAM_BOT_TOKEN')"
            },
            "chat_id": {
              "type": "string",
              "description": "Telegram Chat ID (e.g. '-100123456789' or '$ENV:TELEGRAM_CHAT_ID')"
            }
          },
          "required": ["bot_token", "chat_id"]
        },
        "discord": {
          "type": "object",
          "properties": {
            "webhook_url": {
              "type": "string",
              "description": "Discord Webhook URL (or '$ENV:DISCORD_WEBHOOK_URL')"
            }
          },
          "required": ["webhook_url"]
        }
      },
      "additionalProperties": false
    },

    "characters": {
      "type": "array",
      "description": "EVE characters to monitor, with auth tokens and granted scopes",
      "items": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "description": "EVE Character ID (from SSO /oauth/verify)"
          },
          "name": {
            "type": "string",
            "description": "Display name (optional, for readability)"
          },
          "token": {
            "type": "string",
            "description": "ESI Access Token (or '$ENV:EVE_TOKEN_MAIN'). Expires after ~20min."
          },
          "refresh_token": {
            "type": "string",
            "description": "ESI Refresh Token for automatic renewal (or '$ENV:EVE_REFRESH_MAIN')"
          },
          "client_id": {
            "type": "string",
            "description": "EVE Developer App Client ID (or '$ENV:EVE_CLIENT_ID')"
          },
          "scopes": {
            "type": "array",
            "description": "List of granted ESI scopes. Validated against required scopes during config check.",
            "items": {
              "type": "string"
            },
            "examples": [
              ["esi-wallet.read_character_wallet.v1", "esi-skills.read_skills.v1", "esi-skills.read_skillqueue.v1"]
            ]
          },
          "corporation": {
            "type": "object",
            "description": "Corporation association (optional, otherwise derived from ESI)",
            "properties": {
              "id": { "type": "integer" },
              "name": { "type": "string" }
            }
          },
          "enabled": {
            "type": "boolean",
            "description": "Whether to actively monitor this character",
            "default": true
          }
        },
        "required": ["id", "token", "refresh_token", "client_id", "scopes"]
      },
      "minItems": 1
    },

    "alerts": {
      "type": "object",
      "description": "Real-time alerts via ESI polling. Checks for changes at regular intervals.",
      "properties": {
        "enabled": {
          "type": "boolean",
          "default": true
        },
        "check_interval": {
          "type": "string",
          "description": "Polling interval (e.g. '5m', '15m', '1h')",
          "default": "5m",
          "pattern": "^[0-9]+(s|m|h)$"
        },
        "channels": {
          "type": "array",
          "description": "Which notification channels to use for alerts",
          "items": {
            "type": "string",
            "enum": ["telegram", "discord"]
          }
        },
        "rules": {
          "type": "array",
          "description": "Alert rules. Each rule defines a trigger type with optional thresholds.",
          "items": {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "war_declared",
                  "war_surrendered",
                  "structure_fuel_low",
                  "structure_under_attack",
                  "skill_complete",
                  "wallet_large_deposit",
                  "wallet_large_withdrawal",
                  "contract_expired",
                  "industry_job_complete",
                  "pi_extractor_expired",
                  "clone_jump_available",
                  "mail_received",
                  "killmail"
                ],
                "description": "Alert type. Each type requires specific ESI scopes."
              },
              "severity": {
                "type": "string",
                "enum": ["info", "warning", "critical"],
                "default": "info",
                "description": "Severity level — affects notification formatting and priority"
              },
              "threshold": {
                "type": "number",
                "description": "Numeric threshold (e.g. ISK amount for wallet alerts, fuel hours for structure alerts)"
              },
              "cooldown": {
                "type": "string",
                "description": "Minimum time between repeated alerts of the same type",
                "default": "1h",
                "pattern": "^[0-9]+(s|m|h)$"
              },
              "character_filter": {
                "type": "array",
                "items": { "type": "integer" },
                "description": "Only trigger for specific character IDs. Empty = all characters."
              }
            },
            "required": ["type"]
          }
        }
      },
      "additionalProperties": false
    },

    "reports": {
      "type": "object",
      "description": "Scheduled reports — generated and sent on a cron schedule.",
      "properties": {
        "enabled": {
          "type": "boolean",
          "default": true
        },
        "schedule": {
          "type": "string",
          "description": "Cron expression (e.g. '0 9 * * *' = daily at 9am, '0 9,21 * * *' = 9am and 9pm)",
          "default": "0 9 * * *"
        },
        "timezone": {
          "type": "string",
          "description": "IANA timezone for the cron schedule",
          "default": "Europe/Berlin"
        },
        "channels": {
          "type": "array",
          "items": { "type": "string", "enum": ["telegram", "discord"] }
        },
        "templates": {
          "type": "array",
          "description": "Which reports to generate",
          "items": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "enum": [
                  "net_worth",
                  "skill_queue",
                  "industry_jobs",
                  "market_orders",
                  "wallet_summary",
                  "assets_summary"
                ],
                "description": "Report template name"
              },
              "format": {
                "type": "string",
                "enum": ["short", "detailed"],
                "default": "short",
                "description": "'short' = compact summary, 'detailed' = full report"
              },
              "character_filter": {
                "type": "array",
                "items": { "type": "integer" },
                "description": "Only include specific character IDs. Empty = all characters."
              }
            },
            "required": ["name"]
          }
        }
      },
      "additionalProperties": false
    },

    "market": {
      "type": "object",
      "description": "Price tracking for items with threshold and trend alerts.",
      "properties": {
        "enabled": {
          "type": "boolean",
          "default": true
        },
        "check_interval": {
          "type": "string",
          "description": "Polling interval for market prices",
          "default": "30m",
          "pattern": "^[0-9]+(s|m|h)$"
        },
        "channels": {
          "type": "array",
          "items": { "type": "string", "enum": ["telegram", "discord"] },
          "description": "Where to send market alerts. If empty, falls back to alerts.channels."
        },
        "items": {
          "type": "array",
          "description": "Items to track with price thresholds",
          "items": {
            "type": "object",
            "properties": {
              "type_id": {
                "type": "integer",
                "description": "EVE Type ID (e.g. 44992 = PLEX). Resolve via /universe/types/{id}/"
              },
              "name": {
                "type": "string",
                "description": "Display name of the item"
              },
              "region_id": {
                "type": "integer",
                "description": "Region ID for market data",
                "default": 10000002
              },
              "region_name": {
                "type": "string",
                "description": "Region display name",
                "default": "The Forge"
              },
              "alert_above": {
                "type": "number",
                "description": "Alert when price exceeds this value (ISK)"
              },
              "alert_below": {
                "type": "number",
                "description": "Alert when price drops below this value (ISK)"
              },
              "trend_alert": {
                "type": "object",
                "description": "Percentage price change within a time window",
                "properties": {
                  "change_percent": {
                    "type": "number",
                    "description": "Percentage change that triggers an alert",
                    "default": 10
                  },
                  "time_window": {
                    "type": "string",
                    "description": "Time window for trend calculation",
                    "default": "1h",
                    "pattern": "^[0-9]+(m|h|d)$"
                  }
                }
              },
              "cooldown": {
                "type": "string",
                "description": "Cooldown between market alerts for this item",
                "default": "1h",
                "pattern": "^[0-9]+(s|m|h)$"
              }
            },
            "required": ["type_id", "name"]
          }
        }
      },
      "additionalProperties": false
    }

  },
  "required": ["schema_version", "characters", "notification_channels"],
  "additionalProperties": false
}
```

## File: LICENSE
size: 1104
sha: 66f018485b00596b1d2e5f03c4e4c94d56e17fee
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/LICENSE

```text
MIT License

Copyright (c) 2026 burnshall-ui <https://github.com/burnshall-ui>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

```

## File: tests/test_regressions.py
size: 17715
sha: ccea5926d817cb36fdb21c967d46d78cb1494106
upstream: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/tests/test_regressions.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/burnshall-ui/openclaw-eve-skill/blob/HEAD/tests/test_regressions.py
