akta-pro-cli 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,157 @@
1
+ """Shared request/render plumbing for the akta.pro CLI.
2
+
3
+ - `AppContext` holds the resolved global options (set on `ctx.obj` by the root
4
+ callback).
5
+ - `fetch()` resolves the API key, performs the GET, and maps failures to exit
6
+ codes (0 ok / 2 bad-input / 3 auth / 4 API / 5 timeout).
7
+ - `emit()` renders a result: a file (`-o`), clean JSON (`--json` or a pipe), or
8
+ a human-friendly table/Markdown in a TTY. Credits go to stderr.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import httpx
20
+ import typer
21
+ from rich.markdown import Markdown
22
+
23
+ from akta_pro_cli.client import DEFAULT_BASE_URL, AktaAPIError, AktaClient
24
+ from akta_pro_cli.config import stored_api_key, stored_base_url
25
+ from akta_pro_cli.console import err, out
26
+
27
+ # Exit codes (common CLI convention).
28
+ EXIT_BAD_INPUT = 2
29
+ EXIT_AUTH = 3
30
+ EXIT_API = 4
31
+ EXIT_TIMEOUT = 5
32
+
33
+
34
+ @dataclass
35
+ class AppContext:
36
+ api_key: str | None
37
+ base_url: str | None # from --base-url / AKTA_PRO_API_BASE_URL; None if unset
38
+ quiet: bool
39
+ timeout: float = 30.0
40
+
41
+
42
+ def resolve_base_url(ctx: AppContext) -> str:
43
+ """Effective base URL: explicit flag/env → stored (from `akta-pro login`) → default.
44
+
45
+ Lets local testing target a dev backend either per-command
46
+ (`--base-url http://localhost:8000/api/v1` or the AKTA_PRO_API_BASE_URL env) or
47
+ persistently (`akta-pro login --base-url …`, then every command follows).
48
+ """
49
+ return ctx.base_url or stored_base_url() or DEFAULT_BASE_URL
50
+
51
+
52
+ def resolve_api_key(ctx: AppContext) -> str:
53
+ key = ctx.api_key or stored_api_key()
54
+ if not key:
55
+ err.print(
56
+ "[red]No akta.pro API key found.[/]\n"
57
+ "Provide one with [bold]--api-key[/], the [bold]AKTA_PRO_API_KEY[/] env var, "
58
+ "or run [bold]akta-pro login[/].\n"
59
+ "Get a key at https://playground.akta.pro (API Keys)."
60
+ )
61
+ raise typer.Exit(code=EXIT_AUTH)
62
+ return key
63
+
64
+
65
+ def probe_is_enterprise(ctx: AppContext) -> bool:
66
+ """Best-effort Enterprise-tier check via /mcp/account (free, 0 credits).
67
+
68
+ Returns False on any failure (no key, network error, endpoint not deployed)
69
+ so a probe never blocks or crashes the actual command.
70
+ """
71
+ key = ctx.api_key or stored_api_key()
72
+ if not key:
73
+ return False
74
+ client = AktaClient(resolve_base_url(ctx), key, timeout=ctx.timeout)
75
+ try:
76
+ account = client.get("/mcp/account")
77
+ return bool(account.get("is_enterprise")) if isinstance(account, dict) else False
78
+ except Exception:
79
+ return False
80
+ finally:
81
+ client.close()
82
+
83
+
84
+ def _exit_code_for_status(status: int) -> int:
85
+ if status in (400, 422):
86
+ return EXIT_BAD_INPUT
87
+ if status in (401, 403):
88
+ return EXIT_AUTH
89
+ return EXIT_API
90
+
91
+
92
+ def fetch(ctx: AppContext, path: str, params: dict | None = None) -> Any:
93
+ """Resolve the key, GET `path`, and translate errors into `typer.Exit`."""
94
+ key = resolve_api_key(ctx)
95
+ client = AktaClient(resolve_base_url(ctx), key, timeout=ctx.timeout)
96
+ try:
97
+ return client.get(path, params=params)
98
+ except AktaAPIError as exc:
99
+ err.print(f"[red]Error {exc.status_code}:[/] {exc}")
100
+ raise typer.Exit(code=_exit_code_for_status(exc.status_code)) from exc
101
+ except httpx.TimeoutException as exc:
102
+ err.print("[red]Request timed out.[/]")
103
+ raise typer.Exit(code=EXIT_TIMEOUT) from exc
104
+ except httpx.HTTPError as exc:
105
+ err.print(f"[red]Network error:[/] {exc}")
106
+ raise typer.Exit(code=EXIT_API) from exc
107
+ finally:
108
+ client.close()
109
+
110
+
111
+ def _json_text(result: Any) -> str:
112
+ if isinstance(result, str):
113
+ return result
114
+ return json.dumps(result, indent=2, ensure_ascii=False)
115
+
116
+
117
+ def emit(
118
+ ctx: AppContext,
119
+ result: Any,
120
+ *,
121
+ json_out: bool = False,
122
+ output: Path | None = None,
123
+ renderer: Callable[[Any], Any] | None = None,
124
+ markdown: bool = False,
125
+ ) -> None:
126
+ # 1. credits → stderr (for dict/JSON results). `company data` returns a
127
+ # Markdown string with credits already appended as an in-body footer, so it
128
+ # deliberately doesn't hit this branch — see commands/company.py.
129
+ if isinstance(result, dict) and not ctx.quiet:
130
+ credits = result.get("credits_consumed")
131
+ if credits is not None:
132
+ err.print(f"[dim]credits consumed: {credits}[/]")
133
+
134
+ # 2. file output → raw machine payload
135
+ if output is not None:
136
+ output.write_text(_json_text(result))
137
+ err.print(f"[green]✓[/] wrote {output}")
138
+ return
139
+
140
+ # 3. --json or a non-TTY pipe → clean, un-styled payload on stdout
141
+ if json_out or not out.is_terminal:
142
+ print(_json_text(result))
143
+ return
144
+
145
+ # 4. human/default rendering in a TTY
146
+ if markdown and isinstance(result, str):
147
+ out.print(Markdown(result))
148
+ return
149
+ if renderer is not None:
150
+ renderable = renderer(result)
151
+ if renderable is not None:
152
+ out.print(renderable)
153
+ return
154
+ if isinstance(result, str):
155
+ out.print(result)
156
+ else:
157
+ out.print_json(_json_text(result))
akta_pro_cli/update.py ADDED
@@ -0,0 +1,79 @@
1
+ """Update checking for the CLI.
2
+
3
+ Discovers the latest released version from PyPI (the `akta-pro-cli` project's
4
+ JSON API). Results are cached in the config dir so `akta-pro --version` can show
5
+ a hint without hitting the network on every call.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import time
12
+ import urllib.request
13
+ from pathlib import Path
14
+
15
+ from akta_pro_cli.config import config_dir
16
+
17
+ PACKAGE = "akta-pro-cli"
18
+ PYPI_URL = f"https://pypi.org/pypi/{PACKAGE}/json"
19
+ PROJECT_URL = f"https://pypi.org/project/{PACKAGE}/"
20
+ _CACHE_TTL = 24 * 3600 # re-check at most once a day for the --version hint
21
+
22
+
23
+ def _cache_path() -> Path:
24
+ return config_dir() / "update-check.json"
25
+
26
+
27
+ def parse_version(v: str) -> tuple[int, ...]:
28
+ """Lenient version tuple: '1.2.3' -> (1, 2, 3); non-numeric parts -> 0."""
29
+ parts: list[int] = []
30
+ for chunk in v.split("."):
31
+ digits = ""
32
+ for ch in chunk:
33
+ if ch.isdigit():
34
+ digits += ch
35
+ else:
36
+ break
37
+ parts.append(int(digits) if digits else 0)
38
+ return tuple(parts)
39
+
40
+
41
+ def is_newer(latest: str, current: str) -> bool:
42
+ return parse_version(latest) > parse_version(current)
43
+
44
+
45
+ def latest_version(timeout: float = 5.0) -> str | None:
46
+ """Latest version of the package on PyPI, or None on any failure."""
47
+ try:
48
+ with urllib.request.urlopen(PYPI_URL, timeout=timeout) as resp: # noqa: S310 (https only)
49
+ data = json.load(resp)
50
+ version = data.get("info", {}).get("version")
51
+ return version or None
52
+ except (OSError, ValueError):
53
+ return None
54
+
55
+
56
+ def cached_latest(*, timeout: float = 2.0, ttl: int = _CACHE_TTL, force: bool = False) -> str | None:
57
+ """Latest version string, using a time-boxed cache. Best-effort; None on failure.
58
+
59
+ With `force`, always re-checks (used by `akta-pro update`). Otherwise reads
60
+ the cache and only re-checks once `ttl` has elapsed (used by the `--version`
61
+ hint, so it stays fast and offline most of the time).
62
+ """
63
+ path = _cache_path()
64
+ now = int(time.time())
65
+ if not force:
66
+ try:
67
+ data = json.loads(path.read_text())
68
+ if now - int(data.get("checked_at", 0)) < ttl:
69
+ return data.get("latest")
70
+ except (OSError, ValueError):
71
+ pass
72
+ latest = latest_version(timeout=timeout)
73
+ if latest is not None:
74
+ try:
75
+ path.parent.mkdir(parents=True, exist_ok=True)
76
+ path.write_text(json.dumps({"checked_at": now, "latest": latest}))
77
+ except OSError:
78
+ pass
79
+ return latest
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.4
2
+ Name: akta-pro-cli
3
+ Version: 0.3.0
4
+ Summary: Command-line client for the akta.pro API (api.akta.pro)
5
+ Author-email: Wokelo <support@wokelo.ai>
6
+ Maintainer-email: Wokelo <support@wokelo.ai>
7
+ License: MIT
8
+ Project-URL: Homepage, https://akta.pro/
9
+ Project-URL: Repository, https://github.com/Wokelo-AI/akta-pro-cli
10
+ Keywords: akta-pro,akta.pro,cli,company-intelligence,market-intelligence
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: httpx>=0.27
21
+ Requires-Dist: typer>=0.12
22
+ Requires-Dist: rich>=13
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=8.0; extra == "dev"
25
+ Requires-Dist: respx>=0.22; extra == "dev"
26
+ Requires-Dist: ruff>=0.6; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # akta.pro CLI (`akta-pro`)
30
+
31
+ A command-line client for the akta.pro REST API (`https://api.akta.pro/api/v1`) — a
32
+ sibling of the akta.pro MCP server. Both are thin clients over the same endpoints;
33
+ the CLI is the presentation layer for humans and shell scripts. It ships as its
34
+ own self-contained distribution (`akta-pro-cli`) with no MCP-server code.
35
+
36
+ Source: [`src/akta_pro_cli/`](src/akta_pro_cli). API reference: <https://docs.akta.pro>.
37
+
38
+ ## Install
39
+
40
+ Published on [PyPI](https://pypi.org/project/akta-pro-cli/). Install with `pipx`
41
+ (recommended for CLIs — isolated env) or `pip`:
42
+
43
+ ```bash
44
+ pipx install akta-pro-cli
45
+ # or
46
+ pip install akta-pro-cli
47
+ ```
48
+
49
+ Then run `akta-pro --help`. Full prerequisites, auth, update, and troubleshooting
50
+ steps are in **[INSTALL.md](INSTALL.md)**.
51
+
52
+ The `akta-pro` command depends only on `httpx`, `typer`, `rich`.
53
+
54
+ ## Authentication
55
+
56
+ v1 authenticates with an akta.pro API key (`wk_...`), minted at
57
+ <https://playground.akta.pro> (sign up → **API Keys**). Three ways to supply it,
58
+ in precedence order:
59
+
60
+ ```bash
61
+ akta-pro --api-key wk_... company search Canva # 1. explicit flag
62
+ export AKTA_PRO_API_KEY=wk_... # 2. environment variable
63
+ akta-pro login # 3. stored (prompts, or --api-key)
64
+ ```
65
+
66
+ `akta-pro login` validates the key against a free endpoint and stores it at
67
+ `~/.config/akta-pro/credentials.json` (mode 0600; `%APPDATA%\akta-pro` on Windows).
68
+
69
+ ```bash
70
+ akta-pro login --api-key wk_... # store without the prompt
71
+ akta-pro whoami # show the active key (masked), its source, and validate
72
+ akta-pro logout # remove the stored key
73
+ ```
74
+
75
+ ## Commands
76
+
77
+ | Command | Endpoint | Cost | Notes |
78
+ |---|---|---|---|
79
+ | `akta-pro account` | `/mcp/account` | free | your tier + credit balance |
80
+ | `akta-pro company search <query>` | `/company/search` | free | run first; returns `uuid` |
81
+ | `akta-pro company data <company> -s ...` | `/company/enrichment` (JSON; `--markdown` → `/company/enrichment/markdown`) | per section | requires ≥1 `--section` |
82
+ | `akta-pro company concise <company>` | `/company/enrichment/concise` | 8 | slimmed JSON |
83
+ | `akta-pro industry search <query>` | `/industry/search` | free | codes feed `news signals --industry` |
84
+ | `akta-pro news signals [filters]` | `/news` | 0.1 + 0.01/article | anchor with `--company/--industry/--query/--title` (all optional); rich filters (`--country`, `--entity-*`, `--naics/--sic/--iptc/--iab`, `--blacklist`); compact list with `id`s |
85
+ | `akta-pro news detail <id>...` | `/news/by-id/` | 0.1 + 0.01/article | full bodies for ids from `signals` (max 10) |
86
+ | `akta-pro news types` | none (embedded) | free | tag codes for `--type-code`; offline, no key |
87
+ | `akta-pro headcount <company>` | `/company/headcount-trends` | 2.5 | Subscription/Enterprise |
88
+ | `akta-pro traffic <company>` | `/company/website-traffic` | 1.5 | Subscription/Enterprise |
89
+ | `akta-pro jobs <company>` | `/company/jobs` | 3 | Subscription/Enterprise |
90
+ | `akta-pro posts <company>` | `/company/posts` | 1.5 | Subscription/Enterprise |
91
+ | `akta-pro reviews employees <company>` | `/company/employee-reviews` | 1.5/50 | Subscription/Enterprise; `-n/--limit` max 100 |
92
+ | `akta-pro reviews products <company>` | `/company/product-reviews` | 1.5/50 | catalog first, then `--product-id`; `-n/--limit` max 50 per product |
93
+
94
+ `company data` sections (each billed separately): `firmographic`,
95
+ `business_model`, `company_assessment`, `trust_signal`, `company_hierarchy`,
96
+ `digital_presence`, `financial_estimate`, `location`, `management_profile`,
97
+ `product_offering`, `strategic_signal`, `customer_profile`, `industry`,
98
+ `technology`, plus enterprise-only `funding_detail` (3) and `mna_and_investment`
99
+ (5). There is no "all" — choose explicitly. The two enterprise sections are
100
+ auto-skipped (not an error) for non-enterprise callers, with a note.
101
+
102
+ Run `akta-pro <command> --help` for every flag.
103
+
104
+ ### Examples
105
+
106
+ ```bash
107
+ akta-pro account # check tier + credits
108
+ akta-pro company search "Canva"
109
+ akta-pro company data canva.com -s firmographic -s technology # rendered Markdown
110
+ akta-pro company data canva.com -s firmographic --raw # raw Markdown (pipe/save)
111
+ akta-pro industry search "warehouse automation"
112
+ akta-pro news types # find type codes
113
+ akta-pro news signals --company canva.com -t SD01 -n 20 # product-launch news
114
+ akta-pro news signals --query "crude oil prices" --json | jq '.data[].id'
115
+ akta-pro news detail 12345 12346 # full bodies for those ids
116
+ akta-pro headcount canva.com
117
+ akta-pro reviews products canva.com # list catalog + ids
118
+ akta-pro reviews products canva.com --product-id p_123 -n 50
119
+ ```
120
+
121
+ ## Output & exit codes
122
+
123
+ - **Default (TTY):** a Rich table for list results (search, industry, news),
124
+ rendered Markdown for `company data`, and pretty-printed JSON for nested
125
+ objects.
126
+ - **`--json`:** clean, unstyled JSON on **stdout** (valid for `| jq`). Applied
127
+ automatically when stdout is piped/redirected. For `company data`, `--json`
128
+ (alias `--raw`) emits the raw Markdown.
129
+ - **`-o/--output FILE`:** writes the raw JSON/text payload to a file.
130
+ - **`credits_consumed`** is printed to **stderr** (silence with `-q/--quiet`),
131
+ so it never pollutes piped JSON.
132
+
133
+ Exit codes: `0` success · `2` bad input · `3` auth (no/invalid key or `403`) ·
134
+ `4` other API/network error · `5` timeout.
@@ -0,0 +1,25 @@
1
+ akta_pro_cli/__init__.py,sha256=OBwPyxDbre_e_wmciRr8zh-db_RMJaZQyQPE9CvcNlw,316
2
+ akta_pro_cli/__main__.py,sha256=kdcuSOTtdYhOAR0QKJkY9SFgtIkyB3YSmOvvVK94nJU,638
3
+ akta_pro_cli/app.py,sha256=fq-P1B_V0vvE5v2GNilK-CMYn7eCYV1VuD3IeItzSBw,3163
4
+ akta_pro_cli/client.py,sha256=KWU-dGOFiz54qVmphw4LoeH-qnZM4mfsyC0ZaS2HEI0,3844
5
+ akta_pro_cli/config.py,sha256=SvYArUye0WcNlUUiR0Y4cHhBrRuDt_Ug820VosffCkA,1842
6
+ akta_pro_cli/console.py,sha256=oxySq6_6gNPy-fbvjnt8rIRhAqAUA1nDEI4R6XugJZ4,264
7
+ akta_pro_cli/news_tags.py,sha256=oZnXIuzo5f6FlA_IZCVTpsL4FyG3V89lrTBUBKNc34g,4185
8
+ akta_pro_cli/options.py,sha256=shGc6xLtyObsm6rEgCacQgcFIh6ymZb3sBggmFNHUD4,708
9
+ akta_pro_cli/runtime.py,sha256=29kmlXySXJJBkZFzyZ00VtsONnAmlhY3Vbm7O7ptOC8,5189
10
+ akta_pro_cli/update.py,sha256=3IXcp_KOqPyoK3vFDj4PbAKaWNXFeIrxSDVNSptOUMo,2591
11
+ akta_pro_cli/commands/__init__.py,sha256=Yaj-wId8zogUPsjQNPJsJGMSpMiUAQilmvF3WjcZV98,36
12
+ akta_pro_cli/commands/account.py,sha256=kSE8JG37Llo_zsByHkNimw6OOTBRNQTQTeJ-OltQ9YU,1228
13
+ akta_pro_cli/commands/alternative.py,sha256=Hawd6pbGCLVO1BO49Fv2GFS5WaONp1Bi9FpWkvoSBJc,3914
14
+ akta_pro_cli/commands/auth.py,sha256=_2Rbmf18g1_PMLKtTXnL6kfilh99Iz1nSfc9KpIvtic,4494
15
+ akta_pro_cli/commands/company.py,sha256=g5meZgDJqp16PrOh8C1Fws1-w6enVGn2IF-FdJTbf-M,7211
16
+ akta_pro_cli/commands/config.py,sha256=nar232l1JluTeHBiUcFbyrKRK7iYscl9oaUHySSOnDw,1920
17
+ akta_pro_cli/commands/industry.py,sha256=PGpmVTuWvDHhWvDqU2HUXzjIZyZX8PnF3t7WnOrz7y8,1496
18
+ akta_pro_cli/commands/news.py,sha256=5ofnfYMh6FLDNdEFKx13K09TK-c0b2gxeZK6IU2FgKM,11239
19
+ akta_pro_cli/commands/update.py,sha256=-gk0mx4tdEWRTKxX1VLjmSQ_MvHDQ3wfpoREgvnTyew,2176
20
+ akta_pro_cli-0.3.0.dist-info/licenses/LICENSE,sha256=72c9hARoXXgaVZ_fbzjUM5hASq0kXSZsOOXsBVW2I6o,1066
21
+ akta_pro_cli-0.3.0.dist-info/METADATA,sha256=jPxZPMbudzb-xOfb3Gt1CeErviYM__QaGYGMwLfZ6s4,6549
22
+ akta_pro_cli-0.3.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
23
+ akta_pro_cli-0.3.0.dist-info/entry_points.txt,sha256=svX39q3yjlmN5mYeSAxPO8QQN6twJqE-fGTh7u_StYM,56
24
+ akta_pro_cli-0.3.0.dist-info/top_level.txt,sha256=BKafPuBjQsh-tYCvmE1GOrbE5FEO8D7M3TV9XevubWU,13
25
+ akta_pro_cli-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ akta-pro = akta_pro_cli.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wokelo AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ akta_pro_cli