Metadata-Version: 2.4
Name: periplus-python-sdk
Version: 0.14.0
Summary: Typed Periplus platform client with SQL and notebook integration
License-Expression: AGPL-3.0-only
Project-URL: Repository, https://github.com/Row-Reason/periplus
Project-URL: Issues, https://github.com/Row-Reason/periplus/issues
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: licensing/LICENSE
License-File: licensing/NOTICE
License-File: licensing/README.md
License-File: licensing/THIRD_PARTY_NOTICES.md
Requires-Dist: httpx>=0.28
Requires-Dist: pydantic<3,>=2.12
Requires-Dist: sqlalchemy<3,>=2.0
Provides-Extra: notebook
Requires-Dist: marimo[sql]>=0.24.1; extra == "notebook"
Dynamic: license-file

# Periplus Python SDK

Typed organization operations and SQL access through the Periplus HTTP API.

## 0.14.0: breaking platform API release

Use 0.14.0 with the matching Periplus API release (source `e8f4879` or later).
It intentionally provides no compatibility layer for the 0.13.0 API. Upgrade the
server and clients together; the older production API cannot serve this contract.

- Capture one URL with `client.captures.create(url="https://example.com/")`.
  For several known URLs, use `client.crawls.create(urls=[...])`; add `follow`
  only when links should be discovered. `captures.create(urls=...)` is removed.
- Capture responses expose `request_id` for status/cancellation and `capture_id`
  for inspection and SQL. `captures.inspect(capture_id, view="summary")` gives a
  bounded first look; crawl results are read through `crawls.captures(...)`.
- Read scheduled URLs with `schedules.urls(...)`, replacing `schedules.pages(...)`.
  Scheduled captures are pinned by default for `every_days + 7` days and require
  pin permission. Default retention follows interval edits; explicit retention
  stays fixed. Shortening an interval can shorten retention of existing captures.
- Paid bot-challenge resolution is requested explicitly with
  `resolve_bot_challenges=True`, subject to the organization's allowance.
- Submit API/SDK bug reports through `client.bug_reports.create(...)`.
  Detailed API guidance and inspection results are available in synchronous and
  asynchronous clients.

Historical multi-URL capture requests appear as crawls after the server migration;
their captures, results and project associations are retained. The retired web
search experiment is removed. SQL access and notebook integrations remain available.

## Install

Install from PyPI:

```sh
python -m pip install --upgrade periplus-python-sdk
```

```python
from periplus_sdk import Client

with Client("https://api.periplus.dev", api_key="ppl_…") as client:
    result = client.execute(
        "SELECT capture_id, url FROM public_v1.captures LIMIT ?", [10]
    )
    print(result.columns, result.rows)
```

The default origin is `https://api.periplus.dev`. Use `PERIPLUS_API_URL` to override it and `PERIPLUS_API_KEY` to
supply your personal organization API key. A key with `organization:sql:exec`
is required. Database usernames/passwords and anonymous access are not supported.
Use HTTPS outside loopback development. Connect directly to the API origin,
not the public marketing site.

Version 0.9.0 requires personal API keys instead of database credentials. Create
a Developer key in the app's Access → SDK & API. It inherits your current access in
that organization; SQL requires your membership to have `organization:sql:exec`.
For local development, install `./clients/periplus-python-sdk` from the repository
root and connect to `http://localhost:8000`.

`AsyncClient` accepts the same options. `prepare` explains a SELECT; `execute`
returns typed columns/rows for read-only queries; `execute(..., max_bytes=1_048_576)` bounds the
response (64 KiB–64 MiB, not counting the echoed SQL and parameters): the API withholds trailing rows
with `truncation_reason="max_bytes"` and its `guidance` says how to continue. `schema()` returns
visible tables, column types/descriptions and helper documentation; `schema("capture_text")`
returns only that relation or helper with its full notes, examples and relationships. All SQL uses
`POST /api/v1/sql`; schema discovery uses `GET /api/v1/schema`. ClickHouse enforces
permissions. Buffered SQL reads retry HTTP 502, 503 and 504 up to twice with bounded
backoff starting in 0.12.1. Set `sql_retries=0` to disable this, or choose up to three retries. Each
attempt may observe a newer corpus snapshot. Mutations, transport failures and
streamed queries are not retried automatically.

Public HTML joins use `capture_id` and `node_index`; `document_id` identifies exact
raw bytes. Public shorthand uses the `public_v1` schema.

In 0.10.0, `result.source_snapshot` is a typed `SourceSnapshot` containing
`layout_id` (UUID) and `publication_epoch` (integer), or `None` when no build-bound
public corpus was read. Buffered, asynchronous, streamed and DB-API results share
this contract. Compare both fields, not just the epoch. The identity describes
the public corpus inputs, not any native staff/external inputs. It does not retain
the data or request historical reads. This replaces the old nullable integer field;
use this SDK version with the corresponding API release.

For notebook/SQLAlchemy integration:

```python
from periplus_sdk import sql_api
from sqlalchemy import text

engine = sql_api.create_engine(base_url="http://localhost:8000", api_key="ppl_…")
with engine.connect() as connection:
    print(connection.execute(text("SELECT url FROM public_v1.captures LIMIT 5")).all())
engine.dispose()
```

Marimo discovers accessible tables, views, typed columns and comments through the
schema endpoint. Reflection does not execute SQL. One SQLAlchemy Inspector caches
its metadata; call `inspector.clear_cache()` to refresh it. Missing metadata raises
an error rather than presenting an apparently complete empty schema.

The DB-API connection advertises the ClickHouse dialect and converts native
nullable integer, decimal, date and datetime types. Nested types retain JSON wire
values. Writes are not exposed through the query API. There are no client
transactions; each statement is independent.
Streaming cursors expose incomplete/truncated results explicitly; configure
`allow_partial` only when partial results suit the application.

See [the public schema](../../docs/SCHEMA.md) and [query boundary](../../docs/QUERY.md).

## Organization resources

An API key selects your organization and uses your live membership access. The hosted MCP endpoint uses OAuth sign-in instead of API keys.
`Client` and `AsyncClient` expose the same namespaces:

| Namespace | Operations |
| --- | --- |
| `identity`, `availability` | `get` |
| `captures` | `create`, `get`, `list`, `iter`, `update`, `move`, `cancel`, `batch_cancel` |
| `crawls` | `create`, `get`, `list`, `iter`, `captures`, `update`, `move`, `cancel`, `batch_cancel` |
| `pins` | `create`, `get`, `list`, `iter`, `captures`, `update`, `move`, `delete`, `batch_delete` |
| `schedules` | `create`, `get`, `list`, `iter`, `urls`, `captures`, `update`, `move`, `pause`, `resume`, `delete`, `batch_pause`, `batch_resume`, `batch_delete` |
| `saved_queries` | `create`, `get`, `list`, `iter`, `update`, `rename`, `move`, `delete`, `batch_delete` |
| `projects` | `create`, `get`, `list`, `iter`, `update`, `delete`, `move_items` |
| `members` | `list`, `update_role`, `remove` |
| `invitations` | `list`, `create`, `cancel` |
| `api_keys` | `create`, `list`, `iter`, `revoke` |
| `usage` | `get` |
| `query_history` | `list`, `iter`, `get`, `summary` |
| `audit` | `list`, `iter` |

### Projects

Every saved query, pin, schedule, capture and crawl belongs to exactly one project. The SDK keeps
no active project: pass `project_id` explicitly to each `create`, `update`, `move` and `list` call
where it matters. Items created without `project_id` land in the default project, which is listed
first and cannot be deleted; `move(item, project_id=project)` moves an item (versioned resources
send their current `version`), and `list(project_id=project)` lists one project's items.
Saved queries carry a `version` too: every edit bumps it, and
`saved_queries.update(query_id, sql=..., expected_version=query.version)` raises `ApiError`
409 without changing anything when someone else edited the query since you read it. Omitting
`expected_version` updates whatever the current version is.
`projects.get(project).item_counts` counts each type. Projects own resources, not data: captured
pages stay queryable across the organization.

```python
with Client() as client:
    project = client.projects.create(name="Pricing research", description="Q4 **competitors**")
    crawl = client.crawls.create(urls=["https://example.com/"], follow={"max_depth": 2, "page_limit": 50},
                                 project_id=project)
    pins = client.pins.list(project_id=project).items
    query = client.saved_queries.move(query_id, project_id=project)
    project = client.projects.update(client.projects.get(project), name="Pricing")
    print(project.item_counts.crawls)
```

`projects.delete` only removes empty, non-default projects (409 otherwise).

`projects.move_items(project, items)` moves 1-200 items in one transaction: all of them, or
none. Pass resource objects (`SavedQuery`, `Crawl`, `Pin`, `Schedule`; each sends its
`version` as `expected_version`) or tuples `(kind, id)` / `(kind, id, expected_version)`
with kind `saved_query`, `capture`, `crawl`, `pin` or `schedule`. A missing item, stale version
or missing permission raises `ApiError` (404/409/403) naming the item, and nothing moves. The
`MoveResult` lists `moved` and `unchanged` items (already there) and their `counts`. A schedule's
own pin, and a capture's or crawl's, moves with it. The SDK never splits a move.

Batch methods apply one action to many IDs (or resource objects), each exactly as the
single-item method and independently of the others: `saved_queries.batch_delete`,
`pins.batch_delete`, `schedules.batch_pause` / `batch_resume` / `batch_delete`, and
`captures.batch_cancel` / `crawls.batch_cancel`. They return a `BatchResult` with one result
per ID in order (`ok`, or `error.status` and `error.detail`), plus `succeeded` and `failed`.
More than 200 IDs are sent as several requests; repeated IDs raise `ValueError`.

```python
with Client() as client:
    moved = client.projects.move_items(project, [pin, schedule, ("saved_query", query_id)])
    result = client.pins.batch_delete(old_pins)
    for failure in result.failed:
        print(failure.id, failure.error.status, failure.error.detail)
```

Choose the resource by what you know and how long you need it:

| Resource | Use it when |
| --- | --- |
| `captures` | You want instant feedback on one URL: fetch, wait and summarize |
| `crawls` | You want coverage: any list of up to 1,000 URLs, optionally following links |
| `pins` | You need exact captures for longer than seven days |
| `schedules` | You need the same pages again later |

```python
from periplus_sdk import Client

with Client() as client:
    # wait_seconds (default 40, at most 60) is the total server time for the call: the capture first,
    # then the view. Neither shapes the request; view="summary" needs organization:sql:exec.
    capture = client.captures.create(url="https://example.com/pricing", view="summary")
    if capture.capture_id is None:  # still running: poll the request
        capture = client.captures.get(capture.request_id, wait_seconds=30)
    print(capture.request_id, capture.capture_id, capture.failure, capture.summary or capture.summary_reason)

    # Without follow, a crawl fetches exactly these URLs; with follow it also follows links.
    listed = client.crawls.create(urls=[f"https://example.com/item/{n}" for n in range(500)])
    crawl = client.crawls.create(urls=["https://example.com/docs/"],
                                 follow={"max_depth": 2, "page_limit": 200, "rules": [{"path": "/docs/*"}]})

    pin = client.pins.create(
        name="Research sources", days=90,
        sql="SELECT capture_id FROM captures WHERE domain(url) = ?",
        parameters=["example.com"],
    )
    schedule = client.schedules.create(name="Pricing", every_days=7,
                                       urls=["https://example.com/pricing"])
    print(pin.captures, schedule.projected_captures_per_month)
```

Every capture is kept for seven days after collection unless a pin keeps it. A
capture always fetches again and never returns an existing capture, so check
coverage with SQL first. `request_id` (a capture request's `request_id`, a crawl's `id`)
is what you ordered; `capture_id` (on a capture request once attempted, on each of
`crawls.captures`) is the capture the crawler produced, an observation that succeeded or
failed, and the SQL key. A failed capture keeps its `capture_id`, has a `failure` and is never
`queryable`: it has no page to query. A capture request has one URL; for several
URLs create a crawl without `follow`.
`get(..., wait_seconds=N)` returns as soon as the request is finished and queryable,
or after at most 60 seconds; the SDK never polls on its own. `captures.create` waits up to 40 s by
default (a single capture is typically queryable in about 13 s); pass `wait_seconds=0` to return at
once and poll `get` for longer work.

`captures.inspect(capture_id, view)` reads one existing capture without capturing again
(requires `organization:sql:exec`): `"summary"` is a bounded first look (`CaptureSummary`);
`"metrics"`, `"text"`, `"outline"`, `"structure"` and `"links"` return a `CaptureInspection` page.
Page with `cursor` from the previous page's `next_steps` and the same `limit` (and `max_chars` for text).

```python
first = client.captures.inspect(capture_id, "text", limit=20)
if first.truncated:
    following = client.captures.inspect(capture_id, "text", limit=20,
                                        cursor=first.next_steps[0].arguments["cursor"])
```

`bug_reports.create(title=..., body_markdown=...)` reports Periplus behaving incorrectly;
include operation or request IDs and expected versus actual behaviour, never secrets.

Pins and schedules accept explicit IDs/URLs or one read-only SQL query with
parameters, and are active immediately. SQL runs once at creation and its exact
result is locked in; running the same query beforehand is only an estimate.
Schedule URLs need not be in the corpus. `pin_days` on a capture or crawl pins each
successful capture it produces and requires `organization:pins:write`. A schedule always keeps
each successful capture until the next run plus a week (`pin_days` defaults to `every_days + 7`
and follows later interval changes; pass `pin_days` to set it), so creating one requires
`organization:pins:write` too.
`resolve_bot_challenges=True` on a capture, crawl or schedule asks for paid
bot-challenge resolution (off by default, part of the request's identity); the
organization must allow it (`allow_challenge_resolution`) or the create raises
`ApiError` with code `challenge_resolution_not_allowed` and nothing is accepted.
`pins.update` changes `days` (moving every live capture's expiry by the difference), the
name or the Markdown `description`; `schedules.update` changes `every_days`, the name
or the description (`clear_description=True` removes it). Shortening `days` or `every_days`
can let captures expire at once, and lengthening never revives captures that already expired. Captures and crawls take an
optional `name` and `description` that only label them (a same-ID retry keeps the
first ones); `captures.update`/`crawls.update` change them. Updates accept a fetched
object or an ID with `expected_version`; conflicts are never retried. Deletion needs
no version: deleting a pin removes future protection, not captures.

Paginated lists return `Page[T]` (`items`, `next_cursor`). Cursors are opaque: pass
`next_cursor` unchanged with the same filters, or use `iter()`; lists can shift during
concurrent changes. Membership/invitation lists are bounded snapshots instead. UTC usage ranges have an exclusive end date, at most 93 days. Usage reports pages
captured (broken down by capture, crawl or schedule), challenge-resolution pages and
pinned capture-days.
Query history is best-effort and expires after 30 days; it is not a billing ledger.

`ApiError` includes HTTP status, code, optional request ID, validation fields,
Retry-After seconds and the API's advice: `recovery` text, or for SQL errors `hint`
and `guidance`. Single-item capture, crawl, saved-query and SQL results carry the API's
`guidance`, and capture feeds its `next_steps`: suggested calls by API operation ID, never executed for you. `TransportError` means the outcome of a write can be unknown.
Keep creation IDs to reconcile; never blindly retry. Key creation is one-time:
`created.secret.get_secret_value()` reveals the secret and must only be used for
secure storage. Its ordinary representation is masked. Lost secrets cannot be
recovered.

For async streaming, use `async with await client.stream(sql) as stream` followed
by `async for batch in stream`. Streams validate completion and close on early
exit, errors, and cancellation. No threads or background polling are introduced.
