statement-fetch 0.7.1__tar.gz → 1.2.0__tar.gz

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.
Files changed (32) hide show
  1. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/CHANGELOG.md +30 -0
  2. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/PKG-INFO +14 -12
  3. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/README.md +12 -10
  4. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/pyproject.toml +2 -2
  5. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/__init__.py +12 -0
  6. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/_contracts.py +181 -34
  7. statement_fetch-1.2.0/src/statement_fetch/_diagnostics.py +346 -0
  8. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/_playwright.py +271 -100
  9. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/_registry.py +43 -3
  10. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/_runner.py +231 -169
  11. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/_staging.py +24 -0
  12. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/api.py +12 -0
  13. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/cli.py +76 -24
  14. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/providers/example_bank.py +9 -5
  15. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/tests/test_async_core_and_example.py +430 -25
  16. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/tests/test_demo_e2e_playwright.py +23 -12
  17. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/tests/test_public_hygiene.py +2 -0
  18. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/uv.lock +1 -1
  19. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/.github/workflows/ci.yml +0 -0
  20. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/.github/workflows/pypi.yml +0 -0
  21. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/.github/workflows/release.yml +0 -0
  22. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/.gitignore +0 -0
  23. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/CONTRIBUTING.md +0 -0
  24. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/LICENSE +0 -0
  25. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/Makefile +0 -0
  26. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/SECURITY.md +0 -0
  27. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/_validators.py +0 -0
  28. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/demo.py +0 -0
  29. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/providers/__init__.py +0 -0
  30. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/py.typed +0 -0
  31. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/sinks/__init__.py +0 -0
  32. {statement_fetch-0.7.1 → statement_fetch-1.2.0}/src/statement_fetch/sinks/directory.py +0 -0
@@ -2,6 +2,36 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.2.0] - 2026-12-05
6
+
7
+ ### Added
8
+ - OSS-safe host-boundary diagnostics (`_diagnostics.py`, `FetchResult.diagnostics`, `Stage.note()`) with automatic breadcrumb recording (capped at 25 steps / 4 KiB) and strict URL/token/IBAN/path redaction.
9
+ - Opt-in local CLI `--debug-dir` flag for writing redacted failure diagnostic bundles and `-v`/`--verbose` log level control.
10
+
11
+ ### Fixed
12
+ - Emitted `[provider] stage=...` progress markers to stderr even when `--json` is passed (unless `--quiet`).
13
+
14
+ ### Upgrade
15
+ - Action required: none.
16
+ - Rollback: compatible with `v1.1.0`.
17
+
18
+ ## [1.1.0] - 2026-12-05
19
+
20
+ ### Changed
21
+ - **Breaking:** `API_VERSION = 2` replaces `ProviderSpec(login_url=..., allowed_hosts=...)` with `ProviderSpec(target=Target)` (with read-only compatibility properties preserved on `ProviderSpec`). `Provider[TSession]` and `Host[TTarget, TSessionOut]` are now generic so third-party Android, iOS, desktop, or API ecosystems plug in via `statement_fetch.hosts` without changing core.
22
+
23
+ ### Added
24
+ - Target-agnostic `API_VERSION = 2` plugin contract: open `@runtime_checkable` `Target` protocol (`kind`, `display_label`, `to_dict()`), `WebTarget` (reserved for `kind="web"`), optional `ProviderSpec.session_type` (with `@runtime_checkable` `Page`), `SessionClosedError` (parent of `WindowClosedError`), `HostBusyError` (`host_busy` status, also raised when a `ChromeProfileHost` profile is locked), and formal `LoginWaiter` protocol.
25
+ - `--host auto` default host resolution via `PluginRegistry.default_host_for(target_kind)` and dynamic `statement-fetch host-setup <host>` for any registered host plugin implementing `launch_setup()`.
26
+
27
+ ### Fixed
28
+ - `PluginRegistry.default_host_for()` now normalizes `target_kind` casing, skips broken third-party host entry points, and fails closed when multiple non-web hosts register for the same `target_kind`.
29
+ - `statement-fetch providers --json` error rows now preserve `target_kind`/`target` keys, and `doctor` prioritizes error messages on failing checks.
30
+
31
+ ### Upgrade
32
+ - Action required: plugin authors upgrading from `v0.7.1` (`API_VERSION = 1`) must construct `ProviderSpec(..., target=WebTarget(login_url=..., allowed_hosts=...))` and update custom `Host.open(target)` implementations to accept `WebTarget` (or a custom `Target`).
33
+ - Rollback: compatible with `v1.0.0`.
34
+
5
35
  ## [0.7.1] - 2026-12-05
6
36
 
7
37
  ### Fixed
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: statement-fetch
3
- Version: 0.7.1
4
- Summary: Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated web portals.
3
+ Version: 1.2.0
4
+ Summary: Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated portals and apps.
5
5
  Project-URL: Homepage, https://github.com/benjamin-di/statement-fetch-oss
6
6
  Project-URL: Repository, https://github.com/benjamin-di/statement-fetch-oss
7
7
  Author: benjamin-di
@@ -21,11 +21,11 @@ Description-Content-Type: text/markdown
21
21
 
22
22
  # statement-fetch
23
23
 
24
- Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated web portals.
24
+ Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated portals and apps.
25
25
 
26
26
  ## What It's For
27
27
 
28
- Any web portal behind human login/2FA that periodically issues PDFs, CSVs, JSONs, or ZIP archives can be automated as a small deterministic provider plugin — without ever handing credentials or live portal sessions to an LLM:
28
+ Any authenticated web portal or app behind human login/2FA that periodically issues PDFs, CSVs, JSONs, or ZIP archives can be automated as a small deterministic provider plugin — without ever handing credentials or live sessions to an LLM:
29
29
 
30
30
  - **Banking, cards & brokerage:** monthly statements, transaction CSVs, trade confirmations, custody and tax reports.
31
31
  - **Private funds & wealth portals:** quarterly partner reports, capital calls, distributions, K-1s, and audit letters.
@@ -37,10 +37,10 @@ Any web portal behind human login/2FA that periodically issues PDFs, CSVs, JSONs
37
37
 
38
38
  ## Security Model ("Zero-LLM-in-Portal")
39
39
 
40
- 1. **Human sign-in:** A real Chromium browser opens the portal's login URL. The human completes authentication and 2FA; no credentials or LLM tokens touch the live session.
41
- 2. **Host confinement:** Top-level navigations, HTTP 3xx redirects (single/multi-hop and POST), `target="_blank"` popups, and in-page `fetch_bytes()` calls are confined to the provider's declared `allowed_hosts` via Chromium CDP `Fetch.enable` and context routing.
40
+ 1. **Human sign-in:** A real session host (built-in Chromium/Chrome for web, or a third-party mobile/custom host plugin) opens the target. The human completes authentication and 2FA; no credentials or LLM tokens touch the live session.
41
+ 2. **Per-host confinement:** Each host enforces and documents its own confinement boundary. Built-in `playwright` and `chrome` hosts confine top-level navigations, HTTP 3xx redirects (single/multi-hop and POST), `target="_blank"` popups, and in-page `fetch_bytes()` calls to the provider's declared `WebTarget.allowed_hosts` via Chromium CDP `Fetch.enable` and context routing (`chrome-attach` enforces tab-scoped CDP confinement). Custom/mobile host plugins define and enforce their own target confinement.
42
42
  3. **Deterministic fetch & atomic staging:** After `is_logged_in()` succeeds, deterministic provider code downloads documents into a per-run `0o700` staging directory, validates every artifact using its declared validator (defaulting to non-empty; built-in validators cover PDF, CSV, JSON, and bounded ZIP), writes `0o600` artifacts with SHA-256 digests, and produces a portable `manifest.json`.
43
- 4. **Guaranteed logoff & pluggable sinks:** `logoff()` and browser teardown run in `finally:` even on error or Ctrl-C. Sinks (`statement_fetch.sinks`) verify every manifest entry and SHA-256 before delivering.
43
+ 4. **Guaranteed logoff & pluggable sinks:** `logoff()` and host teardown run in `finally:` even on error or Ctrl-C. Sinks (`statement_fetch.sinks`) verify every manifest entry and SHA-256 before delivering.
44
44
 
45
45
  ## Installation
46
46
 
@@ -104,9 +104,11 @@ statement-fetch fetch example-bank --host chrome --opt base_url=http://127.0.0.1
104
104
  statement-fetch fetch example-bank --host chrome-attach --opt base_url=http://127.0.0.1:8765
105
105
  ```
106
106
 
107
- ## Plugin API (`API_VERSION = 1`)
107
+ ## Plugin API (`API_VERSION = 2`)
108
108
 
109
- Third-party providers, sinks, and browser hosts import from `statement_fetch.api` (or top-level `statement_fetch`) and register via Python entry points:
109
+ `statement-fetch` core is zero-dependency and **target-agnostic**: providers declare any `Target` implementing the open `Target` protocol (`kind`, `display_label`, `to_dict()`), and session hosts declare `target_kind` and register via `statement_fetch.hosts`. Built-in web providers use `WebTarget` + `Page` (with `--host auto` selecting `playwright`); third-party Android, iOS, desktop, or API ecosystems plug in cleanly as separate packages with zero changes to core.
110
+
111
+ Third-party providers, sinks, and session hosts import from `statement_fetch.api` (or top-level `statement_fetch`) and register via Python entry points:
110
112
 
111
113
  ```toml
112
114
  [project.entry-points."statement_fetch.providers"]
@@ -122,12 +124,12 @@ my-host = "my_pkg.host:MyHostPlugin"
122
124
  - Reference provider: `src/statement_fetch/providers/example_bank.py`
123
125
  - Reference sink: `src/statement_fetch/sinks/directory.py`
124
126
  - Built-in hosts: `PlaywrightHostPlugin`, `ChromeHostPlugin`, `CdpChromeHostPlugin` in `statement_fetch.api`
125
- - Versioning: the entry-point group names (`statement_fetch.providers`, `statement_fetch.sinks`, `statement_fetch.hosts`) define the `API_VERSION = 1` compatibility boundary.
127
+ - Versioning: the entry-point group names (`statement_fetch.providers`, `statement_fetch.sinks`, `statement_fetch.hosts`) and `statement_fetch.api` define the `API_VERSION = 2` compatibility boundary.
126
128
 
127
129
  ## CLI Exit Codes & Manifest Schema
128
130
 
129
- - **Exit codes:** `0` (`EXIT_OK`, ok/empty), `1` (`EXIT_ERROR`), `2` (`EXIT_USAGE`), `3` (`EXIT_LOGIN_TIMEOUT`), `4` (`EXIT_PARTIAL`), `130` (interrupted / Ctrl-C).
130
- - **`manifest.json` (`schema_version = 1`):** `schema_version`, `api_version`, `tool_version`, `created_at`, `provider`, `period_start`, `period_end`, `artifacts[]` (`artifact_id`, `name`, `path` relative to manifest dir, `sha256`, `bytes`, `provider`, `kind`, `period`, `valid`, optional `currency`/`error`/`observed_start`/`observed_end`/`meta`), `skipped[]`, `errors[]`, `timings_s`.
131
+ - **Exit codes:** `0` (`EXIT_OK`, ok/empty), `1` (`EXIT_ERROR`, including `host_busy`/`window_closed`), `2` (`EXIT_USAGE`), `3` (`EXIT_LOGIN_TIMEOUT`), `4` (`EXIT_PARTIAL`), `130` (interrupted / Ctrl-C).
132
+ - **`manifest.json` (`schema_version = 1`):** `schema_version`, `api_version`, `tool_version`, `created_at`, `provider`, `period_start`, `period_end`, `artifacts[]` (`artifact_id`, `name`, `path` relative to manifest dir, `sha256`, `bytes`, `provider`, `kind`, `period`, `valid`, optional `currency`/`error`/`observed_start`/`observed_end`/`meta`), `skipped[]`, `errors[]`, `coverage`, `timings_s`.
131
133
 
132
134
  ## Development Checks
133
135
 
@@ -1,10 +1,10 @@
1
1
  # statement-fetch
2
2
 
3
- Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated web portals.
3
+ Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated portals and apps.
4
4
 
5
5
  ## What It's For
6
6
 
7
- Any web portal behind human login/2FA that periodically issues PDFs, CSVs, JSONs, or ZIP archives can be automated as a small deterministic provider plugin — without ever handing credentials or live portal sessions to an LLM:
7
+ Any authenticated web portal or app behind human login/2FA that periodically issues PDFs, CSVs, JSONs, or ZIP archives can be automated as a small deterministic provider plugin — without ever handing credentials or live sessions to an LLM:
8
8
 
9
9
  - **Banking, cards & brokerage:** monthly statements, transaction CSVs, trade confirmations, custody and tax reports.
10
10
  - **Private funds & wealth portals:** quarterly partner reports, capital calls, distributions, K-1s, and audit letters.
@@ -16,10 +16,10 @@ Any web portal behind human login/2FA that periodically issues PDFs, CSVs, JSONs
16
16
 
17
17
  ## Security Model ("Zero-LLM-in-Portal")
18
18
 
19
- 1. **Human sign-in:** A real Chromium browser opens the portal's login URL. The human completes authentication and 2FA; no credentials or LLM tokens touch the live session.
20
- 2. **Host confinement:** Top-level navigations, HTTP 3xx redirects (single/multi-hop and POST), `target="_blank"` popups, and in-page `fetch_bytes()` calls are confined to the provider's declared `allowed_hosts` via Chromium CDP `Fetch.enable` and context routing.
19
+ 1. **Human sign-in:** A real session host (built-in Chromium/Chrome for web, or a third-party mobile/custom host plugin) opens the target. The human completes authentication and 2FA; no credentials or LLM tokens touch the live session.
20
+ 2. **Per-host confinement:** Each host enforces and documents its own confinement boundary. Built-in `playwright` and `chrome` hosts confine top-level navigations, HTTP 3xx redirects (single/multi-hop and POST), `target="_blank"` popups, and in-page `fetch_bytes()` calls to the provider's declared `WebTarget.allowed_hosts` via Chromium CDP `Fetch.enable` and context routing (`chrome-attach` enforces tab-scoped CDP confinement). Custom/mobile host plugins define and enforce their own target confinement.
21
21
  3. **Deterministic fetch & atomic staging:** After `is_logged_in()` succeeds, deterministic provider code downloads documents into a per-run `0o700` staging directory, validates every artifact using its declared validator (defaulting to non-empty; built-in validators cover PDF, CSV, JSON, and bounded ZIP), writes `0o600` artifacts with SHA-256 digests, and produces a portable `manifest.json`.
22
- 4. **Guaranteed logoff & pluggable sinks:** `logoff()` and browser teardown run in `finally:` even on error or Ctrl-C. Sinks (`statement_fetch.sinks`) verify every manifest entry and SHA-256 before delivering.
22
+ 4. **Guaranteed logoff & pluggable sinks:** `logoff()` and host teardown run in `finally:` even on error or Ctrl-C. Sinks (`statement_fetch.sinks`) verify every manifest entry and SHA-256 before delivering.
23
23
 
24
24
  ## Installation
25
25
 
@@ -83,9 +83,11 @@ statement-fetch fetch example-bank --host chrome --opt base_url=http://127.0.0.1
83
83
  statement-fetch fetch example-bank --host chrome-attach --opt base_url=http://127.0.0.1:8765
84
84
  ```
85
85
 
86
- ## Plugin API (`API_VERSION = 1`)
86
+ ## Plugin API (`API_VERSION = 2`)
87
87
 
88
- Third-party providers, sinks, and browser hosts import from `statement_fetch.api` (or top-level `statement_fetch`) and register via Python entry points:
88
+ `statement-fetch` core is zero-dependency and **target-agnostic**: providers declare any `Target` implementing the open `Target` protocol (`kind`, `display_label`, `to_dict()`), and session hosts declare `target_kind` and register via `statement_fetch.hosts`. Built-in web providers use `WebTarget` + `Page` (with `--host auto` selecting `playwright`); third-party Android, iOS, desktop, or API ecosystems plug in cleanly as separate packages with zero changes to core.
89
+
90
+ Third-party providers, sinks, and session hosts import from `statement_fetch.api` (or top-level `statement_fetch`) and register via Python entry points:
89
91
 
90
92
  ```toml
91
93
  [project.entry-points."statement_fetch.providers"]
@@ -101,12 +103,12 @@ my-host = "my_pkg.host:MyHostPlugin"
101
103
  - Reference provider: `src/statement_fetch/providers/example_bank.py`
102
104
  - Reference sink: `src/statement_fetch/sinks/directory.py`
103
105
  - Built-in hosts: `PlaywrightHostPlugin`, `ChromeHostPlugin`, `CdpChromeHostPlugin` in `statement_fetch.api`
104
- - Versioning: the entry-point group names (`statement_fetch.providers`, `statement_fetch.sinks`, `statement_fetch.hosts`) define the `API_VERSION = 1` compatibility boundary.
106
+ - Versioning: the entry-point group names (`statement_fetch.providers`, `statement_fetch.sinks`, `statement_fetch.hosts`) and `statement_fetch.api` define the `API_VERSION = 2` compatibility boundary.
105
107
 
106
108
  ## CLI Exit Codes & Manifest Schema
107
109
 
108
- - **Exit codes:** `0` (`EXIT_OK`, ok/empty), `1` (`EXIT_ERROR`), `2` (`EXIT_USAGE`), `3` (`EXIT_LOGIN_TIMEOUT`), `4` (`EXIT_PARTIAL`), `130` (interrupted / Ctrl-C).
109
- - **`manifest.json` (`schema_version = 1`):** `schema_version`, `api_version`, `tool_version`, `created_at`, `provider`, `period_start`, `period_end`, `artifacts[]` (`artifact_id`, `name`, `path` relative to manifest dir, `sha256`, `bytes`, `provider`, `kind`, `period`, `valid`, optional `currency`/`error`/`observed_start`/`observed_end`/`meta`), `skipped[]`, `errors[]`, `timings_s`.
110
+ - **Exit codes:** `0` (`EXIT_OK`, ok/empty), `1` (`EXIT_ERROR`, including `host_busy`/`window_closed`), `2` (`EXIT_USAGE`), `3` (`EXIT_LOGIN_TIMEOUT`), `4` (`EXIT_PARTIAL`), `130` (interrupted / Ctrl-C).
111
+ - **`manifest.json` (`schema_version = 1`):** `schema_version`, `api_version`, `tool_version`, `created_at`, `provider`, `period_start`, `period_end`, `artifacts[]` (`artifact_id`, `name`, `path` relative to manifest dir, `sha256`, `bytes`, `provider`, `kind`, `period`, `valid`, optional `currency`/`error`/`observed_start`/`observed_end`/`meta`), `skipped[]`, `errors[]`, `coverage`, `timings_s`.
110
112
 
111
113
  ## Development Checks
112
114
 
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "statement-fetch"
7
- version = "0.7.1"
8
- description = "Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated web portals."
7
+ version = "1.2.0"
8
+ description = "Zero-LLM async fetcher, structural validator, and pluggable sink runner for statements, invoices, and documents from authenticated portals and apps."
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  authors = [{ name = "benjamin-di" }]
@@ -32,10 +32,12 @@ from .api import (
32
32
  FetchResult,
33
33
  FrameLocator,
34
34
  Host,
35
+ HostBusyError,
35
36
  HostPlugin,
36
37
  Keyboard,
37
38
  Locator,
38
39
  LoginTimeoutError,
40
+ LoginWaiter,
39
41
  ManifestArtifact,
40
42
  OptionSpec,
41
43
  Page,
@@ -44,12 +46,16 @@ from .api import (
44
46
  PluginRegistry,
45
47
  Provider,
46
48
  ProviderSpec,
49
+ SessionClosedError,
47
50
  Sink,
48
51
  SinkResult,
49
52
  Stage,
53
+ Target,
50
54
  TargetResolvingProvider,
51
55
  ValidationResult,
52
56
  ValidatorFn,
57
+ WebProvider,
58
+ WebTarget,
53
59
  WindowClosedError,
54
60
  iter_verified_manifest_artifacts,
55
61
  load_manifest,
@@ -100,10 +106,12 @@ __all__ = [
100
106
  "FetchResult",
101
107
  "FrameLocator",
102
108
  "Host",
109
+ "HostBusyError",
103
110
  "HostPlugin",
104
111
  "Keyboard",
105
112
  "Locator",
106
113
  "LoginTimeoutError",
114
+ "LoginWaiter",
107
115
  "ManifestArtifact",
108
116
  "OptionSpec",
109
117
  "Page",
@@ -112,12 +120,16 @@ __all__ = [
112
120
  "PluginRegistry",
113
121
  "Provider",
114
122
  "ProviderSpec",
123
+ "SessionClosedError",
115
124
  "Sink",
116
125
  "SinkResult",
117
126
  "Stage",
127
+ "Target",
118
128
  "TargetResolvingProvider",
119
129
  "ValidationResult",
120
130
  "ValidatorFn",
131
+ "WebProvider",
132
+ "WebTarget",
121
133
  "WindowClosedError",
122
134
  "api",
123
135
  "iter_verified_manifest_artifacts",
@@ -2,18 +2,19 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import calendar
5
+ import json
5
6
  import re
6
- from collections.abc import Callable, Mapping
7
+ from collections.abc import Awaitable, Callable, Mapping
7
8
  from dataclasses import dataclass, field
8
9
  from datetime import date, datetime, timedelta
9
10
  from pathlib import Path
10
- from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable
11
+ from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeVar, runtime_checkable
11
12
  from urllib.parse import urlsplit
12
13
 
13
14
  if TYPE_CHECKING:
14
15
  from ._staging import Stage
15
16
 
16
- API_VERSION = 1
17
+ API_VERSION = 2
17
18
  MANIFEST_SCHEMA_VERSION = 1
18
19
  PROVIDER_ENTRY_POINT_GROUP = "statement_fetch.providers"
19
20
  SINK_ENTRY_POINT_GROUP = "statement_fetch.sinks"
@@ -27,6 +28,7 @@ EXIT_PARTIAL = 4
27
28
 
28
29
  _PROVIDER_ID_RE = re.compile(r"^[a-z][a-z0-9-]{0,62}$")
29
30
  _ARTIFACT_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,62}$")
31
+ _TARGET_KIND_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
30
32
  _HOSTNAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$")
31
33
 
32
34
 
@@ -79,8 +81,12 @@ class DownloadMismatchError(RuntimeError):
79
81
  """Raised when a downloaded file does not match the expected suffix or constraints."""
80
82
 
81
83
 
82
- class WindowClosedError(RuntimeError):
83
- """Raised when the browser window is closed before sign-in completes."""
84
+ class SessionClosedError(RuntimeError):
85
+ """Raised when the host session terminates or disconnects before the operation completes."""
86
+
87
+
88
+ class WindowClosedError(SessionClosedError):
89
+ """Raised when the browser window or tab is closed before sign-in completes."""
84
90
 
85
91
 
86
92
  class LoginTimeoutError(TimeoutError):
@@ -91,6 +97,93 @@ class DuplicatePluginError(RuntimeError):
91
97
  """Raised when two plugins register the same provider or sink ID."""
92
98
 
93
99
 
100
+ class HostBusyError(RuntimeError):
101
+ """Raised when a target host resource (browser profile, device, etc.) is already claimed."""
102
+
103
+
104
+ # ---------------------------------------------------------------------------
105
+ # Typed targets
106
+ # ---------------------------------------------------------------------------
107
+
108
+
109
+ @runtime_checkable
110
+ class Target(Protocol):
111
+ """Open protocol for any provider session target (web, mobile, desktop, or custom)."""
112
+
113
+ @property
114
+ def kind(self) -> str: ...
115
+
116
+ @property
117
+ def display_label(self) -> str: ...
118
+
119
+ def to_dict(self) -> dict[str, Any]: ...
120
+
121
+
122
+ def validate_target(target: Any, *, owner: str = "") -> Target:
123
+ """Strictly validate a `Target` implementation (kind, JSON round-trip, display_label, and web reservation)."""
124
+ prefix = f"{owner}: " if owner else ""
125
+ if not isinstance(target, Target):
126
+ raise ValueError(f"{prefix}target must implement Target protocol, got {target!r}")
127
+ kind = target.kind
128
+ if not isinstance(kind, str) or not _TARGET_KIND_RE.fullmatch(kind):
129
+ raise ValueError(f"{prefix}invalid Target.kind {kind!r}; expected lowercase identifier matching ^[a-z][a-z0-9_-]{{0,31}}$")
130
+ if kind == "web" and not isinstance(target, WebTarget):
131
+ raise ValueError(f"{prefix}Target.kind='web' is reserved for WebTarget instances, got {type(target).__name__}")
132
+ label = target.display_label
133
+ if not isinstance(label, str) or not label.strip() or not label.isprintable():
134
+ raise ValueError(f"{prefix}Target.display_label must be a non-empty printable string, got {label!r}")
135
+ to_dict_fn = getattr(target, "to_dict", None)
136
+ if not callable(to_dict_fn):
137
+ raise ValueError(f"{prefix}Target.to_dict must be callable")
138
+ payload = to_dict_fn()
139
+ if not isinstance(payload, dict):
140
+ raise ValueError(f"{prefix}Target.to_dict() must return a dict, got {type(payload).__name__}")
141
+ if payload.get("kind") != kind:
142
+ raise ValueError(f"{prefix}Target.to_dict()['kind'] ({payload.get('kind')!r}) must match Target.kind ({kind!r})")
143
+ try:
144
+ json.dumps(payload, allow_nan=False)
145
+ except (TypeError, ValueError) as exc:
146
+ raise ValueError(f"{prefix}Target.to_dict() must be strictly JSON-serializable: {exc}") from exc
147
+ return target
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class WebTarget:
152
+ """Authenticated web portal target (HTTPS or loopback HTTP)."""
153
+
154
+ login_url: str
155
+ allowed_hosts: tuple[str, ...]
156
+ kind: Literal["web"] = "web"
157
+
158
+ def __post_init__(self) -> None:
159
+ if self.kind != "web":
160
+ raise ValueError(f"WebTarget.kind must be 'web', got {self.kind!r}")
161
+ if not self.allowed_hosts:
162
+ raise ValueError("WebTarget must declare non-empty allowed_hosts.")
163
+ for h in self.allowed_hosts:
164
+ if not is_valid_host(h):
165
+ raise ValueError(f"WebTarget has invalid allowed_host: {h!r}")
166
+ if (
167
+ not self.login_url
168
+ or self.login_url.startswith(("about:", "data:", "blob:"))
169
+ or not allowed_document_url(self.login_url, hosts=self.allowed_hosts)
170
+ ):
171
+ raise ValueError(
172
+ f"WebTarget login_url {self.login_url!r} is not an allowed HTTPS/loopback URL on {self.allowed_hosts!r}"
173
+ )
174
+
175
+ @property
176
+ def display_label(self) -> str:
177
+ return self.login_url
178
+
179
+ def to_dict(self) -> dict[str, Any]:
180
+ return {
181
+ "kind": self.kind,
182
+ "login_url": self.login_url,
183
+ "allowed_hosts": list(self.allowed_hosts),
184
+ }
185
+
186
+
94
187
  # ---------------------------------------------------------------------------
95
188
  # Declarative download triggers
96
189
  # ---------------------------------------------------------------------------
@@ -145,6 +238,7 @@ class Keyboard(Protocol):
145
238
  async def type(self, text: str) -> None: ...
146
239
 
147
240
 
241
+ @runtime_checkable
148
242
  class Page(Protocol):
149
243
  @property
150
244
  def keyboard(self) -> Keyboard: ...
@@ -173,21 +267,44 @@ class Page(Protocol):
173
267
 
174
268
 
175
269
  @runtime_checkable
176
- class Host(Protocol):
270
+ class LoginWaiter(Protocol):
271
+ """Optional session protocol for host-driven login handoff or custom polling."""
272
+
273
+ async def wait_for_login(
274
+ self,
275
+ check_logged_in: Callable[[], Awaitable[bool]],
276
+ *,
277
+ display_name: str,
278
+ timeout_s: float,
279
+ poll_interval: float,
280
+ on_waiting: Callable[[], None],
281
+ is_post_login_url: Callable[[str], bool] | None = None,
282
+ ) -> bool: ...
283
+
284
+
285
+ TTarget = TypeVar("TTarget", contravariant=True)
286
+ TSessionOut = TypeVar("TSessionOut", covariant=True)
287
+ TSession = TypeVar("TSession", contravariant=True)
288
+
289
+
290
+ @runtime_checkable
291
+ class Host(Protocol[TTarget, TSessionOut]):
177
292
  name: str
293
+ target_kind: str
178
294
 
179
- async def open(self, url: str, *, allowed_hosts: tuple[str, ...]) -> Page: ...
295
+ async def open(self, target: TTarget) -> TSessionOut: ...
180
296
  async def close(self) -> None: ...
181
297
 
182
298
 
183
299
  @runtime_checkable
184
300
  class HostPlugin(Protocol):
185
- """Pluggable browser host factory registered via `statement_fetch.hosts` entry points."""
301
+ """Pluggable session host factory registered via `statement_fetch.hosts` entry points."""
186
302
 
187
303
  id: str
304
+ target_kind: str
188
305
 
189
306
  def validate_config(self, config: Mapping[str, str] | None = None) -> None: ...
190
- def create(self, config: Mapping[str, str] | None = None) -> Host: ...
307
+ def create(self, config: Mapping[str, str] | None = None) -> Host[Any, Any]: ...
191
308
  def check_health(self, config: Mapping[str, str] | None = None) -> dict[str, Any]: ...
192
309
 
193
310
 
@@ -271,26 +388,26 @@ class OptionSpec:
271
388
  class ProviderSpec:
272
389
  id: str
273
390
  display_name: str
274
- login_url: str
275
- allowed_hosts: tuple[str, ...]
391
+ target: Target
276
392
  artifacts: tuple[ArtifactSpec, ...]
277
393
  options: tuple[OptionSpec, ...] = ()
278
394
  supports_accounts: bool = False
395
+ session_type: type[Any] | None = None
279
396
 
280
397
  def __post_init__(self) -> None:
281
398
  if not self.id or not _PROVIDER_ID_RE.fullmatch(self.id):
282
399
  raise ValueError(f"Invalid provider id: {self.id!r}")
283
- if not self.allowed_hosts:
284
- raise ValueError(f"Provider {self.id!r} must declare non-empty allowed_hosts.")
285
- for h in self.allowed_hosts:
286
- if not is_valid_host(h):
287
- raise ValueError(f"Provider {self.id!r} has invalid allowed_host: {h!r}")
288
- if not self.login_url or self.login_url.startswith(("about:", "data:", "blob:")) or not allowed_document_url(
289
- self.login_url, hosts=self.allowed_hosts
290
- ):
291
- raise ValueError(
292
- f"Provider {self.id!r} login_url {self.login_url!r} is not an allowed HTTPS/loopback URL on {self.allowed_hosts!r}"
293
- )
400
+ validate_target(self.target, owner=f"Provider {self.id!r}")
401
+ if self.session_type is not None:
402
+ if not isinstance(self.session_type, type):
403
+ raise ValueError(f"Provider {self.id!r} session_type must be a type or None, got {self.session_type!r}")
404
+ if getattr(self.session_type, "_is_protocol", False) and not getattr(
405
+ self.session_type, "_is_runtime_protocol", False
406
+ ):
407
+ raise ValueError(
408
+ f"Provider {self.id!r} session_type {self.session_type.__name__!r} is a Protocol "
409
+ "without @runtime_checkable."
410
+ )
294
411
  if not self.artifacts:
295
412
  raise ValueError(f"Provider {self.id!r} must declare at least one ArtifactSpec.")
296
413
  seen_arts: set[str] = set()
@@ -306,6 +423,18 @@ class ProviderSpec:
306
423
  raise ValueError(f"Provider {self.id!r} declares duplicate option name: {opt.name!r}")
307
424
  seen_opts.add(opt.name)
308
425
 
426
+ @property
427
+ def target_kind(self) -> str:
428
+ return self.target.kind
429
+
430
+ @property
431
+ def login_url(self) -> str:
432
+ return self.target.login_url if isinstance(self.target, WebTarget) else ""
433
+
434
+ @property
435
+ def allowed_hosts(self) -> tuple[str, ...]:
436
+ return self.target.allowed_hosts if isinstance(self.target, WebTarget) else ()
437
+
309
438
  def default_artifact_ids(self) -> tuple[str, ...]:
310
439
  return tuple(a.id for a in self.artifacts if a.default) or tuple(a.id for a in self.artifacts)
311
440
 
@@ -314,11 +443,12 @@ class ProviderSpec:
314
443
 
315
444
  def to_dict(self) -> dict[str, Any]:
316
445
  """Return JSON-serializable capability metadata (excluding validator callables)."""
317
- return {
446
+ payload: dict[str, Any] = {
318
447
  "id": self.id,
319
448
  "display_name": self.display_name,
320
- "login_url": self.login_url,
321
- "allowed_hosts": list(self.allowed_hosts),
449
+ "target_kind": self.target.kind,
450
+ "display_label": self.target.display_label,
451
+ "target": self.target.to_dict(),
322
452
  "artifacts": [
323
453
  {
324
454
  "id": a.id,
@@ -346,6 +476,10 @@ class ProviderSpec:
346
476
  ],
347
477
  "supports_accounts": bool(self.supports_accounts),
348
478
  }
479
+ if isinstance(self.target, WebTarget):
480
+ payload["login_url"] = self.target.login_url
481
+ payload["allowed_hosts"] = list(self.target.allowed_hosts)
482
+ return payload
349
483
 
350
484
  def resolve_artifacts(self, requested: tuple[str, ...] | list[str]) -> tuple[str, ...]:
351
485
  """Resolve requested artifact tokens (supporting `all`/`*` and `ArtifactSpec.aliases`)."""
@@ -411,6 +545,8 @@ class Artifact:
411
545
  observed_start: str = ""
412
546
  observed_end: str = ""
413
547
  meta: dict[str, str] = field(default_factory=dict)
548
+ content_addressed: bool | None = None
549
+ rows: int | None = None
414
550
 
415
551
  def to_manifest_dict(self) -> dict[str, Any]:
416
552
  """Serialize artifact metadata using a portable path relative to `manifest.json`."""
@@ -429,21 +565,29 @@ class Artifact:
429
565
  val = getattr(self, key)
430
566
  if val:
431
567
  out[key] = val
568
+ if self.content_addressed is not None:
569
+ out["content_addressed"] = self.content_addressed
570
+ if self.rows is not None:
571
+ out["rows"] = self.rows
432
572
  if self.meta:
433
573
  out["meta"] = dict(self.meta)
574
+ rel = self.meta.get("rel")
575
+ if rel:
576
+ out["rel"] = rel
434
577
  return out
435
578
 
436
579
 
437
580
  @dataclass(frozen=True)
438
581
  class FetchResult:
439
582
  provider: str
440
- status: Literal["ok", "empty", "partial", "login_timeout", "window_closed", "error"]
583
+ status: Literal["ok", "empty", "partial", "login_timeout", "window_closed", "host_busy", "error"]
441
584
  stage_dir: Path | None
442
585
  manifest_path: Path | None
443
586
  artifacts: tuple[Artifact, ...] = ()
444
587
  skipped: tuple[dict[str, str], ...] = ()
445
588
  errors: tuple[str, ...] = ()
446
589
  timings_s: dict[str, float] = field(default_factory=dict)
590
+ diagnostics: dict[str, Any] = field(default_factory=dict)
447
591
 
448
592
  @property
449
593
  def ok(self) -> bool:
@@ -478,22 +622,25 @@ class SinkResult:
478
622
 
479
623
 
480
624
  @runtime_checkable
481
- class Provider(Protocol):
625
+ class Provider(Protocol[TSession]):
482
626
  spec: ProviderSpec
483
627
 
484
- async def is_logged_in(self, page: Page) -> bool: ...
485
- async def fetch(self, page: Page, req: FetchRequest, stage: Stage) -> None: ...
486
- async def logoff(self, page: Page) -> None: ...
628
+ async def is_logged_in(self, session: TSession) -> bool: ...
629
+ async def fetch(self, session: TSession, req: FetchRequest, stage: Stage) -> None: ...
630
+ async def logoff(self, session: TSession) -> None: ...
487
631
 
488
632
 
489
633
  @runtime_checkable
490
- class AccountsProvider(Provider, Protocol):
491
- async def accounts(self, page: Page, req: AccountsRequest) -> list[AccountInfo]: ...
634
+ class AccountsProvider(Provider[TSession], Protocol):
635
+ async def accounts(self, session: TSession, req: AccountsRequest) -> list[AccountInfo]: ...
492
636
 
493
637
 
494
638
  @runtime_checkable
495
- class TargetResolvingProvider(Provider, Protocol):
496
- def resolve_target(self, req: FetchRequest | AccountsRequest) -> tuple[str, tuple[str, ...]]: ...
639
+ class TargetResolvingProvider(Provider[TSession], Protocol):
640
+ def resolve_target(self, req: FetchRequest | AccountsRequest) -> Target: ...
641
+
642
+
643
+ WebProvider = Provider[Page]
497
644
 
498
645
 
499
646
  @runtime_checkable