Metadata-Version: 2.5
Name: introspection-sdk
Version: 0.44.0
Summary: Python SDK for Introspection — continuously improve your AI systems with production feedback and frontier practices
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: ag-ui-protocol<0.2.0,>=0.1.19
Requires-Dist: httpx2>=2.12.0
Requires-Dist: pydantic>=2.10.0
Provides-Extra: arrow
Requires-Dist: pyarrow>=14.0.0; extra == 'arrow'
Provides-Extra: dev
Requires-Dist: griffe>=2.3.2; extra == 'dev'
Requires-Dist: mypy>=2.4.0; extra == 'dev'
Requires-Dist: pre-commit>=3.5.0; extra == 'dev'
Requires-Dist: ruff==0.14.14; extra == 'dev'
Requires-Dist: ty>=0.0.7; extra == 'dev'
Requires-Dist: unasync==0.6.0; extra == 'dev'
Provides-Extra: otel
Requires-Dist: opentelemetry-exporter-otlp-proto-http<1.43.0,>=1.39.0; extra == 'otel'
Requires-Dist: opentelemetry-sdk<1.43.0,>=1.39.0; extra == 'otel'
Provides-Extra: proxy-httpx
Requires-Dist: httpx<1,>=0.27.0; extra == 'proxy-httpx'
Provides-Extra: test
Requires-Dist: dirty-equals>=0.11.0; extra == 'test'
Requires-Dist: inline-snapshot>=0.31.0; extra == 'test'
Requires-Dist: jsonschema>=4.23.0; extra == 'test'
Requires-Dist: pydantic>=2.12.0; extra == 'test'
Requires-Dist: pytest-asyncio>=1.3.0; extra == 'test'
Requires-Dist: pytest-cov>=7.1.0; extra == 'test'
Requires-Dist: pytest-recording>=0.14.0; extra == 'test'
Requires-Dist: pytest>=9.0.0; extra == 'test'
Requires-Dist: responses>=0.25.8; extra == 'test'
Requires-Dist: trustme>=1.2.0; extra == 'test'
Requires-Dist: vcrpy>=8.3.0; extra == 'test'
Description-Content-Type: text/markdown

<div align="center">
  <a href="https://introspection.dev">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset=".github/images/logo-dark.svg">
      <source media="(prefers-color-scheme: light)" srcset=".github/images/logo-light.svg">
      <img alt="Introspection" src=".github/images/logo-light.svg" width="30%">
    </picture>
  </a>
</div>

<h4 align="center">The infrastructure for long-horizon vertical agents.</h4>

<div align="center">
  <a href="https://introspection.dev"><img src="https://img.shields.io/badge/website-introspection.dev-blue" alt="Website"></a>
  <a href="https://pypi.org/project/introspection-sdk/"><img src="https://img.shields.io/pypi/v/introspection-sdk?label=%20" alt="PyPI version"></a>
  <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/license-Apache%202.0-green" alt="License"></a>
  <a href="https://x.com/IntrospectionAI"><img src="https://img.shields.io/twitter/follow/IntrospectionAI" alt="Follow on X"></a>
</div>

[Introspection](https://introspection.dev) is the infrastructure for
long-horizon vertical agents, powered by Pi. Define an agent as a
[Recipe](https://pi.recipes) — agents, skills, policies, and evals in plain
source you own in Git — deploy it to a governed per-customer Runtime, and
improve it in production with conversations, observations, judges, and
experiments.

This is the Python SDK: run tasks against a deployed runtime, stream their
output, and record what users thought of the result.

## Install

```shell
uv add introspection-sdk
# or
pip install introspection-sdk
```

### Endpoint-binding proxy transports

The default install includes the native `httpx2` adapter:

```python
from introspection_sdk.proxy.httpx2 import IntrospectionTransport
```

Libraries that still use legacy `httpx`, including current Harbor and E2B
releases, can opt into that dependency and import the matching adapter:

```shell
pip install "introspection-sdk[proxy-httpx]"
```

```python
from introspection_sdk.proxy.httpx import IntrospectionTransport
```

Both imports use the same routing implementation and the standard proxy
environment contract: `HTTPS_PROXY`/`HTTP_PROXY` (credentials in the proxy URL
are sent as `Proxy-Authorization`), `NO_PROXY`, and `SSL_CERT_FILE`, which
also verifies an `https://` proxy. Transport types cannot be shared between the
two HTTP libraries, so only their thin library-specific wrappers differ.

Runtimes that predate `INTROSPECTION_EGRESS_PROXY_NATIVE=1` still set
`INTROSPECTION_EGRESS_URL` and `INTROSPECTION_ENDPOINT_HOSTS`; requests to those
hosts are rewritten to the egress. With the native flag set, or without an
egress URL, nothing is rewritten. The rewriting is deprecated and will be
removed.

## Run a task

```python
import asyncio

from introspection_sdk import AsyncIntrospectionClient


async def main() -> None:
    async with AsyncIntrospectionClient() as client:  # token from INTROSPECTION_TOKEN
        runner = await client.runtimes("customer-agent").run()

        async with runner:
            run = await runner.tasks.start(prompt="Say hello in one sentence.")

            async for event in run.stream():
                print(event)


asyncio.run(main())
```

`runtimes("customer-agent").run()` is one request, `POST
/v1/runtimes/customer-agent/run`: the Control Plane resolves the slug in the
credential's project (or the `project=` you pass), so a credential that may not
list runtimes, such as a customer signed in by email code, can still open a
runner. `runner.refresh()` posts the same path. A UUID selector is a runtime
group id; it is resolved with `GET /v1/runtimes` first, and
`client.runtimes.handle(runtime_id)` posts a known runtime id directly.

`client.runtimes.list()`, `get(runtime_id)` and `resolve(slug_or_id)` return a
`Runtime` that says where it comes from. A server that predates a field leaves
it at its default:

| Field | What it holds |
| --- | --- |
| `runtime_group_type` | `RuntimeGroupType.MANAGED` for a first-party runtime Introspection owns, `RuntimeGroupType.CUSTOM` (default) for any other |
| `template_ref` | The template the runtime group was created from, or `None` |
| `image_revision` / `image_commit_subject` | For an image version: the recipe commit its image carries and that commit's subject line |
| `image_repository` | The recipe's GitHub repository (`owner/name`) |

```python
from introspection_sdk.schemas.runtimes import RuntimeGroupType

runtime = client.runtimes.resolve("customer-agent")
if runtime.runtime_group_type is RuntimeGroupType.MANAGED:
    print(f"managed, from template {runtime.template_ref}")
```

Or wait for the finished answer instead of streaming:

```python
run = await runner.tasks.start(prompt="Summarize my open tickets.")
print(await run.text())
```

Continue the same task with a follow-up run:

```python
follow_up = await runner.tasks.runs.create(
    str(run.run.task_id),
    kind="prompt",
    prompt={"text": "Now draft the reply."},
)
print(await follow_up.text())
```

`IntrospectionClient` is the synchronous twin with the same surface — drop the
`await`s and use `for` instead of `async for`.

See [Tasks and streaming](https://docs.introspection.dev/sdk/python/tasks-and-streaming) for reconnects,
interrupts, and cancellation.

## Record feedback

Install the OpenTelemetry extra, then attach the outcome to the conversation
the agent produced:

```shell
pip install 'introspection-sdk[otel]'
```

```python
from introspection_sdk import IntrospectionLogs

logs = IntrospectionLogs(service_name="support-api")

with logs.identify("user_123", traits={"plan": "pro"}):
    with logs.set_conversation(conversation_id):
        logs.feedback("thumbs_up", comments="The answer solved it")

logs.track("case_closed", {"source": "web"})
logs.shutdown()
```

`feedback` records how a result landed, `track` records a product event, and
`identify` attaches who it was.

To record an app event under your own name (`ark.feed.entry`), use
`logs.log_event(name, attributes, event_id=...)`; `track` is an alias of it.
See [Logging custom events](docs/otel.md#logging-custom-events) for
idempotency, reserved names, use from a recipe sandbox, and reading events
back.

See [Product signals](https://docs.introspection.dev/sdk/python/product-signals) for the full surface, and
[**`docs/otel.md`**](docs/otel.md) for the OTel wiring.

## Read what happened

A finished task leaves a durable conversation. Add immutable, filter-only
metadata when creating the task, then use the same keys to find it later:

```python
await runner.tasks.create(
    prompt="Handle this checkout",
    conversation_metadata={"flow": "checkout", "tenant": "acme"},
)

async for summary in runner.conversations.list(
    limit=20,
    metadata={"flow": "checkout"},
):
    print(summary.id, summary.usage.total_tokens, summary.cost.usd)
```

The runner also exposes `files`, `shares`, `events`, `metrics`,
`routines`, `issues` and `connections`.

## Export a conversation's spans

`client.conversations.export_jsonl(conversation_id)` reads the whole
conversation as JSON lines (`application/x-ndjson`): one GenAI span per line,
each line a complete JSON object. It yields each span as its line arrives, so
the export is never held in memory whole:

```python
for span in client.conversations.export_jsonl(conversation_id):
    print(span.span_id, span.name, span.model)
```

`export_stream(conversation_id, "jsonl")` yields the same response as raw
bytes, to write to a `.jsonl` file. The JSON-envelope export, `export_json`,
was removed; `export_trajectory` and `export_arrow` are unchanged.

`include=["annotations", "comments"]` also sets `span.annotation`, the span's
row from `client.annotations.list`, on every annotated span, with its
comments. It needs the annotations read scope.

## Export a conversation as a Harbor trajectory

`spans_to_atif` projects the GenAI spans of a conversation onto one
ATIF trajectory, the format Harbor reads. It is a pure function of the spans and needs no
`harbor` install:

```python
from pathlib import Path

from introspection_sdk.atif import spans_to_atif

spans = client.conversations.export_jsonl(conversation_id)
trajectory = spans_to_atif(spans, session_id=conversation_id)
Path("trajectory.json").write_text(trajectory.model_dump_json(indent=2))
```

Each model call becomes one `agent` step with its text, reasoning, tool
calls, usage and cost, and each tool result is attached to the step that made
the call. A total in `final_metrics` is set only when every model call
reported it. For a streamed read, `AtifProjection` takes one span at a time
and returns the steps that are final. Runnable:
[`conversation_atif.py`](examples/introspection_examples/api/conversation_atif.py).

## One data-plane interface on the client and the Runner

`IntrospectionClient` and `Runner` expose the same data-plane namespaces:
`tasks` (with `tasks.runs`), `files`, `conversations`, `events`, `metrics`,
`shares`, `routines`, `issues` and `connections`. The contract is
`introspection_sdk.protocols.DataPlaneResources` (and
`AsyncDataPlaneResources` for `AsyncIntrospectionClient` / `AsyncRunner`),
so code written against it runs with either handle:

```python
from introspection_sdk.protocols import DataPlaneResources


def connected_apps(dp: DataPlaneResources) -> list[str]:
    return [connection.app for connection in dp.connections.list()]


connected_apps(client)                               # the client's own token
connected_apps(client.runtimes("support-agent").run())  # the runner's token
```

The two differ only in the credential they send: the client sends its own
token (an API key, a service account or a member's token) against
`dp_url`, and a Runner sends the session token minted for it. A route the
credential lacks the scope for answers 403 either way. A runner a member
opens for themself is being given `routines:read` and
`routines:write`, so it manages that member's routines.

## Curate traces with human review

Annotations are append-only events on an OTel trace/span. Each write changes
exactly one dimension; label and reviewer lists are complete snapshots, so an
empty list clears that dimension.

```python
from introspection_sdk import IntrospectionClient

client = IntrospectionClient(
    token=member_access_token,
    cp_session=encoded_member_session,
    base_api_url="https://api.introspection.dev",
    dp_url="https://dp.example",
)

client.annotations.create(
    trace_id="0af7651916cd43dd8448eb211c80319c",
    span_id="b7ad6b7169203331",
    reviewer_emails=["expert@example.com"],
)
client.annotations.create(
    trace_id="0af7651916cd43dd8448eb211c80319c",
    span_id="b7ad6b7169203331",
    comment="The answer missed the governing exception.",
)

for item in client.annotations.list(label="needs-review"):
    print(item.trace_id, item.span_id, item.labels, item.comment_count)
```

A listed row carries the labels, assignees, reviewers and comment count of a
span, with `comments` left `None`. `include=["comments"]` sets it on every
row, oldest first:

```python
for item in client.annotations.list(include=["comments"]):
    for comment in item.comments or []:
        print(comment.created_at, comment.member_id, comment.comment)
```

`list(label=..., limit=1, include_total=True).page().total_count` is the size
of a dataset, and `lookback_days` (1 to 90, default 90) bounds how far back
the read reaches.

Reusable labels live in `client.project_labels`; their slug and color are
immutable after creation, while the optional description can be updated.

## Browse repositories

`client.repositories` lists the Git repositories linked to a project and reads
their contents at one resolved commit through the data plane:

```python
repo = client.repositories.list(slug="acme/support")[0]

for entry in client.repositories.contents(repo.id, "agents", ref="main"):
    print(entry.type, entry.path)

readme = client.repositories.contents.get(repo.id, "README.md")
print(readme.type, readme.commit_sha)
```

Iterating `contents()` follows the page cursor; `contents.get()` returns a
`RepositoryDirectory` page or a `RepositoryFile`, discriminated on `type`.

History pages the same way, and one commit carries its changed files and diff:

```python
for commit in client.repositories.commits(repo.id, sha="main", path="agents"):
    print(commit.sha[:7], commit.message.splitlines()[0])

detail = client.repositories.commit(repo.id, commit.sha)
print([f.filename for f in detail.files], len(detail.patch))
```

Merging mirrors GitHub's merges API: `head` is a branch or a full commit sha,
and `None` means `base` already contains it. A conflict raises
`ConflictError` with nothing changed.

```python
merge = client.repositories.merges.create(repo.id, "main", "feature")
if merge is not None:
    print(merge.sha, merge.parents)
```

`branches(repo.id)` pages the branches with their head commits. A hosted
repository is created with `create(slug, project=...)` and served at its `url`
once `provisioning_status` is `ready`; `delete(repo.id)` unlinks one.

## Author recipes and runtimes

`client.recipes.create(...)` pins a recipe to one commit of a repository, and
`client.runtimes.create(...)` makes a runtime version from it. The `slug` names
the runtime group: an existing group gains the version as its next one, which
shares the group's `runtime_group_id`. `update(...)` sends only the fields
given, and `delete(...)` removes a version (the group's live version takes its
siblings with it).

```python
from introspection_sdk.schemas.runtimes import RuntimeInclude

head_sha = client.repositories.commits(repo.id, sha="main").page().records[0].sha
recipe = client.recipes.create(
    project="support",
    repository_id=repo.id,
    name="support-agent",
    git_ref="main",
    git_commit_sha=head_sha,
)
runtime = client.runtimes.create(
    project="support",
    recipe_id=recipe.id,
    name="support-agent",
    slug="support-agent",
)
print(runtime.runtime_group_id, runtime.image_build_status)
requirements = client.runtimes.get(
    runtime.id, include=[RuntimeInclude.MCP_REQUIREMENTS]
).mcp_requirements
```

`client.endpoints` creates, lists, reads, updates and deletes the upstream hosts a
project's runtimes reach; an MCP server's endpoint is the one a connection
binds (`list(mcp_server_id=...)`).
[`author_runtime.py`](examples/introspection_examples/api/author_runtime.py)
runs this flow end to end.

## Label members

`client.members` reads and updates the organization's members. Each carries
two label sets: `tags` are **access-bearing** (a member is admitted by every
share whose `granted_tag` it holds, so writing them needs `members:manage`),
while `metadata` is a `key: value` map that **grants nothing** and exists to
filter on. The older implicit grant, where a member reaches every file and task
whose tags intersect its own, still works but is being retired; share with a
cohort through `shares.create(..., granted_tag="team:acme")` instead.

```python
for member in client.members.list(metadata={"plan": "enterprise"}, tag="team:acme"):
    print(member.id, member.metadata)

member = client.members.update(member_id, metadata={"plan": "pro", "region": "eu"})
client.members.update(member_id, metadata={})  # clear it
```

## Share files, issues and conversations

`shares` grants access to a resource you own. The grantee fields are ANDed:
`granted_member_id` admits one member, `granted_tag` admits everyone whose
token carries that tag (you must hold it), both admit that member only while
they hold the tag, and neither shares with the whole project. A share
admits; the caller's token scopes decide whether they may read, write or
delete. Shares are ambient, so a shared resource shows up in the grantee's
ordinary reads.

```python
share = client.shares.create(
    resource_type="file", resource_id=file_id, granted_tag="team:acme"
)

# On a conversation, `visible_from` hides earlier spans; `update` changes only it.
convo = client.shares.create(
    resource_type="conversation", resource_id=conversation_id, visible_from=cutoff
)
client.shares.update(str(convo.id), visible_from=None)  # clear the cutoff
```

`update` replaces `tags` and `metadata` wholesale: omit a field to leave it,
pass `[]` / `{}` to clear it. The `metadata` filter ANDs up to 16 pairs with
distinct keys, each matched exactly. Keys are letters, digits, `_` and `-`
(no `.`); values are non-empty strings; one write carries at most 64 entries. The
server answers 422 otherwise.

`create` invites a human by email and can seed both sets. A `customer` member
is minted from an asserted identity instead, and that identity can label it:

```python
runner = client.runtimes("customer-agent").run(
    identity={"user_id": "u_123", "metadata": {"plan": "enterprise"}},
)
```

Identity `metadata` seeds a new member and is merged into an existing one,
overwriting keys of the same name (including ones an admin set) and keeping
the rest; `refresh()` re-sends it. Identity `tags`, by contrast, apply only
when the member is created.

See [Production evidence](https://docs.introspection.dev/sdk/python/production-evidence) for transcripts,
typed events, and metrics queries, [Files and shares](https://docs.introspection.dev/sdk/python/files-and-shares)
for durable inputs and grants, and [`examples/`](examples/introspection_examples/)
for end-to-end scripts.

## Authenticate

An API key (`INTROSPECTION_TOKEN`) is the simplest credential. To issue tokens
yourself, register an Application in the project. Its type is chosen at
creation, cannot change, and gives it exactly one way in; an app that needs two
ways in registers two Applications.

| Type              | Who signs in                                         | Grants (`allowed_grants`)                     | SDK entry point                                                               |
| ----------------- | ---------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------- |
| `service_account` | Your server, with a `client_secret`                  | `client_credentials`                          | `IntrospectionClient.from_service_account(...)`, `service_account_token(...)` |
| `jwks`            | Your end users, through your own identity provider   | none: RFC 8693 token exchange of their JWT    | `token_exchange(...)`                                                         |
| `spa`             | Your end users, through Introspection's hosted login | `authorization_code` (PKCE), `refresh_token`  | `authorization_code_token(...)`                                               |
| `native`          | Your end users, with a code sent to their email      | `email_code`, `device_code`, `refresh_token`  | `EmailCodeAuth`, `AsyncEmailCodeAuth`                                         |

The server derives an Application's grants from its type; a client never sends
them. An `spa` needs at least one `redirect_uris` entry and a `jwks` takes none;
an `spa` with a brokered identity provider also exchanges that login's
`id_token` through `token_exchange`. Applications created before the types
became exclusive keep working as they did. Tokens for end users belong to a
`customer` member and carry at most the Application's `allowed_scopes`. A
`service_account` or `jwks` token is not refreshable: mint or exchange again
before `expires_in` lapses.

### Native email-code sign-in

```python
from introspection_sdk import EmailCodeAuth

auth = EmailCodeAuth(client_id="intro_app_...", project="ark")
auth.send_code("user@example.com")
auth.verify_code("user@example.com", code)  # six digits, or six letters and digits on a first sign-in

client = auth.client()  # Data Plane URL from the session
for event in client.events.list("introspection.feedback", limit=5):
    print(event.payload.name)
```

`EmailCodeAuth` refreshes the access token `leeway` seconds (default 60) before
it expires and after a `401`, and concurrent callers share one refresh. A
refresh the server rejects signs the user out and raises `AuthenticationError`.
A sign-in or refresh response that arrives after a newer sign-in or a sign-out
is dropped and raises `SignInSupersededError`, so it never overwrites the newer
session. Pass `session=` to restore a saved `AuthSession` and
`on_session_change=` to persist each change (`None` after `sign_out()`); the
session holds the refresh token, so store it as a secret. A rate-limited
`send_code` raises `RateLimitError` with `retry_after`.

The token is a Data Plane credential: Data Plane namespaces such as
`client.events` accept it within the Application's `allowed_scopes`, and
Control Plane namespaces such as `client.runtimes` reject it. `AsyncEmailCodeAuth` is the asyncio twin, and
`send_email_code`, `email_code_token`, `refresh_access_token` and
`revoke_session` are the one-shot calls underneath. See
[`examples/introspection_examples/api/native_email_code.py`](examples/introspection_examples/api/native_email_code.py).

## Schedule routines

`client.routines` manages a project's routines on the data plane: a
prompt on a schedule (`kind=None`), or platform work (`observation_synthesis`,
`observation_clustering`, `project_check_in`). A prompt routine creates a
task per firing, or posts into an existing task when it names `task_id`. A
one-off reminder is a `manual` routine with a future `next_trigger_at`:

```python
from datetime import UTC, datetime

from introspection_sdk.schemas.routines import RoutineMetadata

reminder = client.routines.create(
    name="Friday check-in",
    trigger_type="manual",
    prompt="How did the week go?",
    runtime_group_id=runtime_group_id,
    task_id=task_id,
    next_trigger_at=datetime(2026, 10, 9, 16, tzinfo=UTC),
)

weekly = client.routines.create(
    name="Weekly digest",
    trigger_type="cron",
    cron_schedule="0 9 * * 1",
    prompt="Summarize my week",
    runtime_group_id=runtime_group_id,
    metadata=RoutineMetadata(timezone="Europe/London"),
)

for routine in client.routines.list(enabled=True, scheduled=True):
    print(routine.name, routine.kind, routine.next_trigger_at)

client.routines.update(weekly.id, enabled=False)  # pause, keep the slot
result = client.routines.trigger(weekly.id)       # run it now
print(result.status, result.task_id, result.reason)
```

`trigger` takes optional `parameters`: a dict (at most 16 KiB as JSON and
8 levels deep, else 422); a local JSON file holding one (a `str` or path),
which the SDK reads and sends as that dict; or an already-uploaded Files API
file holding one (a `File` or its `UUID`). Each `@parameters.<name>` in a prompt routine's
prompt is replaced by that value as JSON (`null` when absent). For a routine
that starts its own task, the SDK first uploads the object through the Files
API (a unique `routine-parameters/<uuid>.json`, expiring after 30 days) and
attaches it to the run as `parameters.json`, so a trigger is two requests.
A platform routine (it has a `kind`) or one that posts into an existing task
takes no files and is sent `parameters` alone; the SDK reads the routine to
tell which, unless you say with `attach_parameters_file=True` / `False`.
A platform routine reads its kind's own keys:

```python
client.routines.trigger(weekly.id, parameters={"customer": "acme", "days": 7})

# A local JSON file: read, then sent exactly as the dict above.
client.routines.trigger(weekly.id, parameters="runs/acme.json")

# Parameters already in the Files API (a JSON object, at most 256 KiB), plus
# inputs. Only the reference is sent: no upload, and the routine is not read.
spec = client.files.create_text(
    name="runs/acme.json", content='{"customer": "acme"}', mime_type="application/json"
)
client.routines.trigger(
    weekly.id,
    parameters=spec,                             # or its UUID, spec.id
    files=[{"id": brief_id, "name": "brief.md"}],  # attached to the run's task
)

synthesis = next(iter(client.routines.list(kind="observation_synthesis")))
queued = client.routines.trigger(
    synthesis.id, parameters={"conversation_ids": ["conv-1"]}
)
print(queued.result)  # {"enqueued": 1, "conversations": [...]}
```

### Start a routine from an event

A prompt routine that starts a task per run can also run on events: its
`triggers` list a Slack or GitHub integration's events, or the calls a
`webhook` connector receives. A webhook connector is inbound only: your own
systems call the control plane's `/v1/webhooks/connectors/{id}`, signed with
[Standard Webhooks](https://www.standardwebhooks.com/) (the default) or
sending `Authorization: Bearer <secret>`, by the type of its secret. It is
created without one, so it refuses every call until you issue a secret; the
platform generates it and returns it once, as a `SecretStr`:

```python
from introspection_sdk.schemas.routines import RoutineTriggerSpec

orders = client.connectors.create(
    name="Orders", slug="orders", provider="webhook", auth_mode="static"
)
issued = client.connectors.secrets.create(
    orders.id, type="standard_webhooks"  # or "bearer"
)
save(issued.secret.get_secret_value())  # shown once

follow_up = client.routines.create(
    name="Order follow-up",
    trigger_type="manual",
    prompt="An order was placed: @parameters.data. Check stock for it.",
    runtime_group_id=runtime_group_id,
    triggers=[
        RoutineTriggerSpec(
            source="connector",
            provider="webhook",
            connector_slug="orders",
            event_types=["order.created"],  # the body's `type`; "*" for any
            filter={"payload_fields": {"region": ["eu"]}},
        )
    ],
)
```

Your system signs each call with the
[`standardwebhooks`](https://pypi.org/project/standardwebhooks/) package:

```python
from datetime import datetime, timezone

from standardwebhooks import Webhook

body = '{"type": "order.created", "region": "eu", "data": {"id": "ord_1"}}'
msg_id = "msg_1"
signature = Webhook(secret).sign(msg_id, datetime.now(timezone.utc), body)
# POST body with webhook-id: msg_1, webhook-timestamp, webhook-signature
```

A trigger declares no parameters: the run it starts receives the event's body
as `parameters.json` (any JSON; a non-JSON body arrives as a JSON string), and
`@parameters.<key>` reads its top-level keys, the same as a manual run's
`parameters`. A key with no value is listed in the task's
`unresolved_parameters` metadata; the event itself stays in
`trigger/event.json`. The task's
`trigger_source` metadata is `trigger` and its `routine_trigger` names the
trigger, event type and delivery. `update(triggers=[...])` replaces the list:
an entry with an existing trigger's `id` keeps it, and `[]` removes them all.
A trigger runs one task at a time; an event that arrives while its run is in
flight is recorded as `introspection.routines.skipped` with reason
`trigger_busy`.

A webhook connector's secrets are the `client.connectors.secrets`
sub-resource. `secrets.create(orders.id)` without a `type` rotates: it issues
a new secret of the live one's type, returned once, and the secret it replaces
keeps working as the previous one until you delete it, so your senders can
switch over. At most two are live, so a rotation with two live is a 409; the
current secret can be deleted only once no previous one is, and deleting the
last leaves the endpoint refusing every call. To change type, delete every
secret, then create one of the other type (a `type` other than the live
secrets' is a 409; no `type` with none live is a 422). `secrets.list` pages
through them, current first, as `WebhookSecret` (`{id, type, status,
created_at}`) without their material; `id` is the kid to delete. Any other
connector answers 404.

```python
rotated = client.connectors.secrets.create(orders.id)
save(rotated.secret.get_secret_value())
current, previous = client.connectors.secrets.list(orders.id)
client.connectors.secrets.delete(orders.id, previous.id)
```

`update` sends only the fields you pass, so `None` never clears anything;
`metadata` replaces wholesale, and `kind` is immutable. `trigger_type`
switches a prompt routine between `manual` and `cron`: `cron` needs a
`cron_schedule` (or `metadata.cron_schedules`) in the same update, and
`manual` drops the next slot.
`delete` soft-deletes, except for a project default, which answers 409:
disable it instead. `kind`, `trigger_type`, condition types, skip reasons and
trigger statuses are open enums: a value this SDK does not know yet decodes
as a plain string rather than failing.

Each firing is recorded as an event, read like any other family:

```python
for event in client.events.list(
    "introspection.routines.triggered", routine_id=weekly.id
):
    print(event.payload.slot, event.payload.task_id, event.payload.posted)
```

`introspection.routines.skipped` records a scheduled slot or an event
delivery that ran nothing, with its `reason`; a run or skip an event trigger
answered carries `payload.event` (`trigger_id`, `event_type`, `delivery_id`).
It is project-owned, so only callers with project-wide
telemetry access read it. Both families take the `routine_id` and
`task_id` filters.

Today the server serves `/v1/routines` to project administrators only and
answers anyone else with a 403. introspection-cloud#3137 (not yet shipped)
opens the routes to members for their own routines that post into one of
their own tasks, and adds the `task_id` list filter, which this SDK already
sends.

The routes need the `routines:read` and `routines:write` scopes, so a `native` sign-in cannot use them yet.
`can_manage` says whether the caller may change a routine, and
`created_by_member_id` who created it.

## Track issues

`client.issues` / `runner.issues` manage a project's issues on the data
plane. An issue is a brief (title, description, priority, status) on a fixed
worker task, which carries its chat, with the people on it (a creator, an
assignee, a reviewer and followers), the evidence it cites (files, links,
events, spans) and its comments.

```python
from introspection_sdk.schemas.issues import IssueStatus, IssueUpdate

issue = client.issues.create(
    title="Checkout times out",
    description="Stripe calls exceed 30s under load.",
    task_id=task_id,
)

# Ask a member: assign the issue, move it to waiting, post the question.
client.issues.update(
    issue.id,
    IssueUpdate(assignee_member_id=member_id, status=IssueStatus.WAITING),
)
client.issues.comments.create(issue.id, comment="Ship the retry?")

# Read the answer: comments come back with the issue, oldest first.
issue = client.issues.get(issue.id, include=["members", "comments"])
for comment in issue.comments or []:
    print(comment.created_at, comment.member_id, comment.comment)

# Unassign and close, refused if the issue changed since this read.
client.issues.update(
    issue.id,
    IssueUpdate(assignee_member_id=None, status=IssueStatus.CLOSED),
    if_match=issue.etag,
)

# What is waiting on the caller.
for issue in client.issues.list(relation=["assignee", "reviewer"]):
    print(issue.display_index, issue.title, issue.assignee_member_id)
```

A read returns the brief, with `created_by_member_id`, `assignee_member_id`
and `reviewer_member_id`. The related lists come back only when `include`
names them, and are `None` otherwise: `members`, `attachments` (`links`,
`files`, `events`, `spans`) and, on `get` only, `comments` (at most 500; page
the issue's events for more). `list`, `create` and `update` take `members`
and `attachments`.

`update` takes an `IssueUpdate` and sends only the fields set on it: an
omitted field is left as it is, `[]` clears a list (`{}` for `metadata`), and
an explicit `None` for `assignee_member_id` or `reviewer_member_id` clears
that person. `follower_member_ids` replaces the followers wholesale. `update`
and `delete` take an optional `if_match`, the `issue.etag` of the read the
write was made against; if the issue changed since, the server answers 412
(`IntrospectionAPIError` with `status_code == 412`), so read it again before
retrying. Without `if_match` the write applies regardless. A comment does not
change the issue's `etag`.

On `list`, `relation` repeats and ORs: on its own it keeps the issues the
caller is on in one of those relations, and with `member_id` that member's.
`status`, `owner`, `task_status` and `metadata` filters repeat on the query
string too. Runnable:
[`issues.py`](examples/introspection_examples/api/issues.py).

Each change to an issue, and each comment, is an `introspection.issue` event.
Its `payload` is a union on `action`: `created` carries `data`, `updated`
carries `changes` (field name to `before` / `after`), `commented` carries
`comment`, and `deleted` nothing more. Each names the `member_id` who made
it. `issue_id` reads one issue's history:

```python
for event in client.events.list("introspection.issue", issue_id=issue.id):
    print(event.timestamp, event.payload.action, event.payload.member_id)
```

## Connect apps for a member

`client.connections` / `runner.connections` manage the apps (Gmail, Slack, …)
members connected for themselves, which the agent then acts with in that
member's sessions. They are the SDK's one connections namespace: a member's
own account through an organization integration (Google Workspace,
Microsoft 365) and a connector's project connection are read and deleted
here too.

```python
page = runner.connections.create(app="gmail")  # runtime: the runner's group
print(page.authorize_url, page.expires_in)     # open it once; never cache it

for connection in runner.connections.list(app="gmail"):
    print(connection.id, connection.account_name, connection.healthy)

runner.connections.delete(connection.id)
```

On the client, `create` takes the runtime explicitly:
`client.connections.create(app="gmail", runtime="support-agent")`, a runtime
slug or runtime group id. `create(integration_id=...)` connects the caller's
own account through an organization integration instead, and takes no
runtime; a project lets its agents use those accounts by naming the
integration types in `connection_integrations` on `client.projects.create` /
`update`. `list` takes `member_id`, `app`, `connector_id`, `integration_id`
and `search` (an account name such as an email contains it) filters; a
caller who is not a project administrator only ever gets their own
connections. The routes need `connections:read`, `connections:write` and
`connections:delete`.

## Run an AAuth Person Server or Access Server

[`introspection-aauth`](packages/introspection-aauth) is a separate package
in this repository: an AAuth Person Server and Access Server
(draft-hardt-oauth-aauth-protocol -11) over a store you provide, with
FastAPI routers. `examples/introspection_examples/aauth/four_party.py` runs
the four-party flow in one process.

A project's own Data Plane keeps the missions its people approved agents to
carry out and the approvals agents asked them for: `client.aauth.missions.list()`
and `client.aauth.approvals.list(status=["pending"])` read them, `get(id)` reads
one, and `client.aauth.approvals.decide(id, status="denied", member_id=...)`
records the approver's answer, as
[`aauth_inbox.py`](examples/introspection_examples/api/aauth_inbox.py) does.

## Administer a project

These Control Plane namespaces need an org credential: an owner's or admin's
session (`IntrospectionClient(cp_session=...)`) or an access token minted for
one. A project API key carries none of their scopes. Pass `project=` (a slug
or id) on project-scoped calls when the credential does not name one.

| Namespace | What it manages |
| --- | --- |
| `client.oidc.me()` | Who the credential is, with the org's resolved feature flags |
| `client.organizations.me()` | The credential's organization: name, slug, whether it hosts Git |
| `client.projects` | The org's projects by slug or id: `list`, `get`, `create(deployment_id=...)`, `update`, `delete` |
| `client.projects.peerings` | The runtime groups a project offers other projects: `list(project, runtime=None)`, `list(project, granted=True)` for those offered to it, `get(project, peering_id)`. Read-only: peerings are written in the web app |
| `client.tokens.create(project=...)` | A signed-in member's access token for one project, with that member's scopes there |
| `client.api_keys` | A project's API keys: `create` returns the plaintext once; `delete(expires_in=...)` rotates |
| `client.applications` | OAuth clients, with `.idps`, `.secrets` and `.keys` under each |
| `client.credentials` / `client.variables` | Secrets and environment variables a project's runtimes read |
| `client.integrations` | The org's own provider installs (org-wide, no `project`) |
| `client.integrations.repositories(id)` | The repositories a GitHub integration's installation can reach, read with the control plane's own credential, in one response ([`project_admin.py`](examples/introspection_examples/api/project_admin.py)) |
| `client.integrations.access_token(id, request=None)` | A short-lived provider token for an integration, never stored server-side; `request` is a `GitHubAccessTokenRequest` (default `metadata: read`, the server's cap today) ([`project_admin.py`](examples/introspection_examples/api/project_admin.py)) |
| `client.judges` | The judges a Recipe declares: read, and toggle `enabled` / `sample_rate` |
| `client.endpoints` | The upstream hosts a project's runtimes reach: `list`, `get`, `create` (an upsert), `update`, `delete` |
| `client.repositories.access_token(id)` | A short-lived Git provider token for a repository; only a sandbox's token gets one ([`repositories.py`](examples/introspection_examples/api/repositories.py)) |
| `client.remotes.connect_docs()` | The `/v1/remotes/connect` WebSocket `introspection dev` dials out on: authentication, handshake and frames ([`remotes.py`](examples/introspection_examples/api/remotes.py)) |
| `introspection_sdk.auth` | The device-code login `introspection login` runs ([`device_login.py`](examples/introspection_examples/api/device_login.py)): `request_device_code`, `poll_device_token`, `wait_for_device_token`, `development_credential`, `oidc_logout` |

```python
client = IntrospectionClient(cp_session=os.environ["INTROSPECTION_CP_SESSION"])

created = client.api_keys.create(project="support", name="ci")
save(created.api_key.get_secret_value())  # a SecretStr: it never prints

client.credentials.create(name="OPENAI_API_KEY", secret="sk-...", project="support")
```

A secret the API returns once (an API key, a client secret) or takes on write
(a credential, an IdP client secret, an integration's OAuth `code`) is a
pydantic `SecretStr`, so `repr` and logging show `**********`.

## Images and task commands

`images` and `tasks.commands` are on the Data Plane, on the client and a
Runner alike, for evaluation trials on a plane with evals enabled. An image is
what an eval task's compose services run as; a command is `exec`, `upload` or
`download` against an eval task's live sandbox.

```python
from introspection_sdk.schemas.images import MirrorImageSource
from introspection_sdk.schemas.task_commands import ExecCommand

image = client.images.create(
    name="hello-mcp/mcp-server",
    source=MirrorImageSource(reference="ghcr.io/acme/mcp@sha256:..."),
)
# Poll client.images.get(image.id) until status is "ready".

task = client.tasks.create(prompt="Fix the failing test", kind="eval", commands=True)
command = client.tasks.commands.create(str(task.task.id), ExecCommand(command=["pytest", "-q"]))
command = client.tasks.commands.get(str(task.task.id), command.id, wait_seconds=25)
print(command.status, command.exit_code, command.stdout)
```

`wait_seconds` holds the read until the command finishes; it is capped at
`MAX_COMMAND_WAIT_SECONDS` (25, below the client's 30-second request timeout),
so call `get` again to wait longer.

## Environment variables

```shell
export INTROSPECTION_TOKEN="intro_xxx"
export INTROSPECTION_BASE_API_URL="https://api.introspection.dev"  # optional
export INTROSPECTION_SERVICE_NAME="my-service"   # optional
export INTROSPECTION_LOG_LEVEL="debug"           # optional
export INTROSPECTION_STRICT_SCHEMA=1             # optional, see below
```

### Catch API drift with `INTROSPECTION_STRICT_SCHEMA`

By default a response field this SDK version does not model is tolerated, so
a server that adds a field never breaks your client. With
`INTROSPECTION_STRICT_SCHEMA=1`, the same response raises `SchemaDriftError`
(an `IntrospectionAPIError`), naming the route and every unmodelled field by
its JSON path:

```text
/v1/tags: response fields this SDK does not model: $.records[0].color, $.cursor_v2
```

The SDK's end-to-end walk runs strict, and so does the platform's SDK coverage
run against a live stack, so a field the API adds shows up there before a
release ships without it. Keys in maps that are open by design are never
reported: a field typed as a `dict` (span `resource`, endpoint `metadata`,
...), the `gen_ai.*` span attributes and the attribute families the SDK does
not type, and the GenAI message and part types. `error.fields` lists the
paths and `error.path` the route.

## Documentation

- [Python quickstart](https://docs.introspection.dev/sdk/python/quickstart)
- [Tasks and streaming](https://docs.introspection.dev/sdk/python/tasks-and-streaming)
- [Files and shares](https://docs.introspection.dev/sdk/python/files-and-shares)
- [Production evidence](https://docs.introspection.dev/sdk/python/production-evidence)
- [Product signals](https://docs.introspection.dev/sdk/python/product-signals)
- [Platform operations](https://docs.introspection.dev/sdk/python/platform-operations)
- [Python SDK reference](https://docs.introspection.dev/sdk/python/reference)
- [Authentication](https://docs.introspection.dev/sdk/authentication)

## License

Apache-2.0
