> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hexagon.autos/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK reference

The current package is `hexagon-agent-sdk` version `0.1.0`, imported as `hexagon`, requiring Python 3.10+. Install from this checkout until a verified public distribution is available:

```sh theme={null}
python3 -m venv .venv
. .venv/bin/activate
python3 -m pip install ./sdk/python
```

The client uses synchronous standard-library HTTP calls. It is not an async client; calls and stream iteration block the calling thread. Package version alone does not identify every development snapshot. Record your installed artifact alongside the server revision. See [package metadata](https://github.com/NexusFox88/docs/blob/main/resources/sdk/python/pyproject.toml).

## Client and identity

```python theme={null}
import os
from hexagon import Hexagon, HexagonError

# Local control plane already started; discovers a private workspace identity.
client = Hexagon.local()

# Alternative for a remote control plane; use only in a trusted backend.
# client = Hexagon(os.environ['HEXAGON_API_URL'],
#                  os.environ['HEXAGON_API_TOKEN'], timeout=90)
```

`base_url` is the control-plane origin without `/v1`; the client appends `/v1`. The constructor does not validate credentials by making a request. `timeout` defaults to 90 seconds and applies to HTTP operations, including reads; it is not a Run execution deadline.

`local(data_directory=None, base_url=None, timeout=90)` reads local discovery and owner files. Explicit data directory selects that workspace; otherwise discovery checks the workspace and configured/user descriptor. The optional base URL checks endpoint consistency rather than turning local mode into remote authentication. Private-file/loopback checks can fail before HTTP. See [local.py](https://github.com/NexusFox88/docs/blob/main/resources/sdk/python/hexagon/local.py). Local calls disable redirects; explicit clients use urllib's default redirect behavior, so configure the actual trusted origin without relying on redirects.

No client-wide `close()` or async context manager exists. `client.close(session_id)` closes a Session and initiates its resource lifecycle; it is not HTTP-client disposal. Ordinary responses use context managers internally. Explicitly close a partially consumed generator if you retain it; stopping observation does not cancel a Run.

## Public method inventory

The following signatures and request expressions are generated from the Python AST, including keyword-only parameters and defaults. Paths are SDK expressions: `{...}` denotes values inserted/encoded by the implementation. Except binary downloads, event generators, constructors and HTTP 204, methods return the JSON-decoded HTTP value (normally a dict), without typed model-object conversion. Collection envelopes remain intact, for example `events()['events']` and `artifacts()['artifacts']`; there is no automatic pagination.

| Signature (self/cls omitted) | HTTP mapping / return mode | Call context |
| - | - | - |
| `local(*, data_directory=None, base_url=None, timeout=90)` | Local discovery → Hexagon instance / 本地发现 | [Contract/errors](https://docs.hexagon.autos/en/operate/local-workspace.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#client-and-identity) |
| `__init__(base_url, token, timeout=90)` | Hexagon instance; no HTTP request / 无请求 | [Contract/errors](https://docs.hexagon.autos/en/operate/local-workspace.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#client-and-identity) |
| `request(method, path, body=None, headers=None)` | JSON-decoded value; 204 → None | [Contract/errors](https://docs.hexagon.autos/en/reference/http.md) · [Example](https://docs.hexagon.autos/en/reference/monitoring.md) |
| `create_preview(session_id, port, ttl_seconds=600)` | `POST` `f"/sessions/{quote(session_id, safe='')}/previews"` | [Contract/errors](https://docs.hexagon.autos/en/reference/artifacts-previews.md) · [Example](https://docs.hexagon.autos/en/build/private-preview.md) |
| `revoke_preview(preview_id)` | `DELETE` `f"/previews/{quote(preview_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/artifacts-previews.md) · [Example](https://docs.hexagon.autos/en/build/private-preview.md) |
| `register_harness(*, image, **configuration)` | `POST` `'/harnesses'` | [Contract/errors](https://docs.hexagon.autos/en/reference/harness-registration.md) · [Example](https://docs.hexagon.autos/en/integrations/harnesses/oci.md) |
| `register_harness_package(**package)` | `POST` `'/harness-packages'` | [Contract/errors](https://docs.hexagon.autos/en/reference/harness-registration.md) · [Example](https://docs.hexagon.autos/en/integrations/harnesses/source-package.md) |
| `catalog()` | `GET` `'/catalog'` | [Contract/errors](https://docs.hexagon.autos/en/reference/harness-registration.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#catalogs-and-oauth-consent-calls) |
| `applications()` | `GET` `'/applications'` | [Contract/errors](https://docs.hexagon.autos/en/reference/oauth.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#catalogs-and-oauth-consent-calls) |
| `configure_application_oauth(provider, **configuration)` | `PUT` `f"/applications/{quote(provider, safe='')}/oauth-client"` | [Contract/errors](https://docs.hexagon.autos/en/reference/oauth.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#catalogs-and-oauth-consent-calls) |
| `authorize_connection(connection_id)` | `POST` `f"/connections/{quote(connection_id, safe='')}/authorize"` | [Contract/errors](https://docs.hexagon.autos/en/reference/oauth.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#catalogs-and-oauth-consent-calls) |
| `authorization_flow(flow_id)` | `GET` `f"/authorization-flows/{quote(flow_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/oauth.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#catalogs-and-oauth-consent-calls) |
| `cancel_authorization(flow_id)` | `DELETE` `f"/authorization-flows/{quote(flow_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/oauth.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#catalogs-and-oauth-consent-calls) |
| `create_secret(*, name, value)` | `POST` `'/secrets'` | [Contract/errors](https://docs.hexagon.autos/en/reference/secrets.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `session_environment(session_id)` | `GET` `f"/sessions/{quote(session_id, safe='')}/environment"` | [Contract/errors](https://docs.hexagon.autos/en/reference/session-access.md) · [Example](https://docs.hexagon.autos/en/reference/session-access.md) |
| `session_authorization(session_id)` | `GET` `f"/sessions/{quote(session_id, safe='')}/authorization"` | [Contract/errors](https://docs.hexagon.autos/en/reference/session-access.md) · [Example](https://docs.hexagon.autos/en/reference/session-access.md) |
| `revoke_session_connection(session_id, connection_id)` | `DELETE` `f"/sessions/{quote(session_id, safe='')}/connections/{quote(connection_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/session-access.md) · [Example](https://docs.hexagon.autos/en/reference/session-access.md) |
| `list_secrets()` | `GET` `'/secrets'` | [Contract/errors](https://docs.hexagon.autos/en/reference/secrets.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `secret(secret_id)` | `GET` `f"/secrets/{quote(secret_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/secrets.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `update_secret(secret_id, **changes)` | `PATCH` `f"/secrets/{quote(secret_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/secrets.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `delete_secret(secret_id)` | `DELETE` `f"/secrets/{quote(secret_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/secrets.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `create_access(session, connection_id)` | `POST` `f"/sessions/{quote(session, safe='')}/access"` | [Contract/errors](https://docs.hexagon.autos/en/reference/session-access.md) · [Example](https://docs.hexagon.autos/en/reference/session-access.md) |
| `list_access(session)` | `GET` `f"/sessions/{quote(session, safe='')}/access"` | [Contract/errors](https://docs.hexagon.autos/en/reference/session-access.md) · [Example](https://docs.hexagon.autos/en/reference/session-access.md) |
| `revoke_access(grant_id)` | `DELETE` `f"/access/{quote(grant_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/session-access.md) · [Example](https://docs.hexagon.autos/en/reference/session-access.md) |
| `overview()` | `GET` `'/overview'` | [Contract/errors](https://docs.hexagon.autos/en/reference/monitoring.md) · [Example](https://docs.hexagon.autos/en/reference/monitoring.md) |
| `list_sessions(**query)` | `GET` `'/sessions?' + urlencode(query)` | [Contract/errors](https://docs.hexagon.autos/en/reference/monitoring.md) · [Example](https://docs.hexagon.autos/en/reference/monitoring.md) |
| `list_runs(**query)` | `GET` `'/runs?' + urlencode(query)` | [Contract/errors](https://docs.hexagon.autos/en/reference/runs.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#read-bounded-pages-of-run-summaries) |
| `pending(limit=25, offset=0)` | `GET` `f'/pending?limit={limit}&offset={offset}'` | [Contract/errors](https://docs.hexagon.autos/en/reference/monitoring.md) · [Example](https://docs.hexagon.autos/en/reference/monitoring.md) |
| `approvals(run_id)` | `GET` `f"/runs/{quote(run_id, safe='')}/approvals"` | [Contract/errors](https://docs.hexagon.autos/en/reference/approvals-tools.md) · [Example](https://docs.hexagon.autos/en/build/approvals.md) |
| `connection_dependencies(connection_id)` | `GET` `f"/connections/{quote(connection_id, safe='')}/dependencies"` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `list_tokens()` | `GET` `'/tokens'` | [Contract/errors](https://docs.hexagon.autos/en/reference/tokens.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `create_token(label, expires_in_days=30)` | `POST` `'/tokens'` | [Contract/errors](https://docs.hexagon.autos/en/reference/tokens.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `rotate_token(token_id)` | `POST` `f"/tokens/{quote(token_id, safe='')}/rotate"` | [Contract/errors](https://docs.hexagon.autos/en/reference/tokens.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `revoke_token(token_id)` | `DELETE` `f"/tokens/{quote(token_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/tokens.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#managed-secret-and-application-token-calls) |
| `deployment()` | `GET` `'/deployment'` | [Contract/errors](https://docs.hexagon.autos/en/reference/deployment.md) · [Example](https://docs.hexagon.autos/en/reference/deployment.md) |
| `update_deployment(config, expected_revision)` | `PUT` `'/deployment'` | [Contract/errors](https://docs.hexagon.autos/en/reference/deployment.md) · [Example](https://docs.hexagon.autos/en/reference/deployment.md) |
| `retry_ingress()` | `POST` `'/deployment/ingress/retry'` | [Contract/errors](https://docs.hexagon.autos/en/reference/deployment.md) · [Example](https://docs.hexagon.autos/en/reference/deployment.md) |
| `resource_operations(limit=50, offset=0)` | `GET` `f'/resource-operations?limit={limit}&offset={offset}'` | [Contract/errors](https://docs.hexagon.autos/en/reference/resource-operations.md) · [Example](https://docs.hexagon.autos/en/operate/reconciliation.md) |
| `resource_operation(operation_id)` | `GET` `f"/resource-operations/{quote(operation_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/resource-operations.md) · [Example](https://docs.hexagon.autos/en/operate/reconciliation.md) |
| `review_resource_operation(operation_id, action, note='')` | `POST` `f"/resource-operations/{quote(operation_id, safe='')}/review"` | [Contract/errors](https://docs.hexagon.autos/en/reference/resource-operations.md) · [Example](https://docs.hexagon.autos/en/operate/reconciliation.md) |
| `list_agents()` | `GET` `'/agents'` | [Contract/errors](https://docs.hexagon.autos/en/reference/agents.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `agent(agent_id)` | `GET` `f"/agents/{quote(agent_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/agents.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `revise_agent(agent_id, definition, expected_revision)` | `PUT` `f"/agents/{quote(agent_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/agents.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `archive_agent(agent_id)` | `POST` `f"/agents/{quote(agent_id, safe='')}/archive"` | [Contract/errors](https://docs.hexagon.autos/en/reference/agents.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `copy_agent(agent_id, name)` | `POST` `f"/agents/{quote(agent_id, safe='')}/copy"` | [Contract/errors](https://docs.hexagon.autos/en/reference/agents.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `preflight_agent(definition, bindings)` | `POST` `'/agents/preflight'` | [Contract/errors](https://docs.hexagon.autos/en/reference/agents.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `preflight_session(**definition)` | `POST` `'/sessions/preflight'` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://docs.hexagon.autos/en/build/sandbox-policy.md) |
| `list_connections()` | `GET` `'/connections'` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `connection(connection_id)` | `GET` `f"/connections/{quote(connection_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `create_connection(**definition)` | `POST` `'/connections'` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `discover_mcp_tools(connection_id)` | `POST` `f"/connections/{quote(connection_id, safe='')}/discover-mcp"` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `connection_authorization(connection_id)` | `GET` `f"/connections/{quote(connection_id, safe='')}/authorization"` | [Contract/errors](https://docs.hexagon.autos/en/reference/oauth.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#catalogs-and-oauth-consent-calls) |
| `disconnect_connection(connection_id)` | `POST` `f"/connections/{quote(connection_id, safe='')}/disconnect"` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `validate_connection(connection_id)` | `POST` `f"/connections/{quote(connection_id, safe='')}/validate"` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `update_connection(connection_id, **changes)` | `PATCH` `f"/connections/{quote(connection_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `delete_connection(connection_id)` | `DELETE` `f"/connections/{quote(connection_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/connections.md) · [Example](https://docs.hexagon.autos/en/reference/python.md#connection-lifecycle-calls) |
| `create_agent(*, env=None, **definition)` | `POST` `'/agents'` | [Contract/errors](https://docs.hexagon.autos/en/reference/agents.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `create_session(*, env=None, **definition)` | `POST` `'/sessions'` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/first-session.py) |
| `session_initialization(session_id)` | `GET` `f"/sessions/{quote(session_id, safe='')}/initialization"` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://docs.hexagon.autos/en/build/agent-templates.md) |
| `session(session_id)` | `GET` `f"/sessions/{quote(session_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/inspect-run.py) |
| `upload(session_id, files)` | `POST` `f"/sessions/{quote(session_id, safe='')}/files"` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://docs.hexagon.autos/en/build/project-context.md) |
| `submit(session_id, text, idempotency_key, *, origin=None)` | `POST` `f"/sessions/{quote(session_id, safe='')}/runs"` | [Contract/errors](https://docs.hexagon.autos/en/reference/runs.md) · [Example](https://docs.hexagon.autos/en/build/backend-integration.md) |
| `run(run_id)` | `GET` `f"/runs/{quote(run_id, safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/runs.md) · [Example](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/inspect-run.py) |
| `tool_calls(run_id)` | `GET` `f"/runs/{quote(run_id, safe='')}/tool-calls"` | [Contract/errors](https://docs.hexagon.autos/en/reference/approvals-tools.md) · [Example](https://docs.hexagon.autos/en/build/tool-authorization.md) |
| `deny_tool_authorization(run_id, call_id, request_hash)` | `POST` `f"/runs/{quote(run_id, safe='')}/tool-calls/{quote(call_id, safe='')}/deny-authorization"` | [Contract/errors](https://docs.hexagon.autos/en/reference/approvals-tools.md) · [Example](https://docs.hexagon.autos/en/build/tool-authorization.md) |
| `resolve_tool_call(run_id, call_id, **resolution)` | `POST` `f"/runs/{quote(run_id, safe='')}/tool-calls/{quote(call_id, safe='')}/resolve"` | [Contract/errors](https://docs.hexagon.autos/en/reference/approvals-tools.md) · [Example](https://docs.hexagon.autos/en/reference/approvals-tools.md) |
| `cancel(run_id)` | `POST` `f"/runs/{quote(run_id, safe='')}/cancel"` | [Contract/errors](https://docs.hexagon.autos/en/reference/runs.md) · [Example](https://docs.hexagon.autos/en/build/recovery.md) |
| `pause(session_id, scope='session')` | `POST` `f"/sessions/{quote(session_id, safe='')}/pause"` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://docs.hexagon.autos/en/build/idle-and-wake.md) |
| `resume(session_id)` | `POST` `f"/sessions/{quote(session_id, safe='')}/resume"` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://docs.hexagon.autos/en/build/idle-and-wake.md) |
| `session_activity(period='24h')` | `GET` `f'/sessions/activity?period={period}'` | [Contract/errors](https://docs.hexagon.autos/en/reference/monitoring.md) · [Example](https://docs.hexagon.autos/en/reference/monitoring.md) |
| `close(session_id)` | `POST` `f"/sessions/{quote(session_id, safe='')}/close"` | [Contract/errors](https://docs.hexagon.autos/en/reference/sessions.md) · [Example](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/first-session.py) |
| `decide(approval_id, approved)` | `POST` `f"/approvals/{quote(approval_id, safe='')}/decision"` | [Contract/errors](https://docs.hexagon.autos/en/reference/approvals-tools.md) · [Example](https://docs.hexagon.autos/en/build/approvals.md) |
| `events(run_id, after='0')` | `GET` `f"/runs/{quote(run_id, safe='')}/events?after={quote(str(after), safe='')}"` | [Contract/errors](https://docs.hexagon.autos/en/reference/runs.md) · [Example](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/inspect-run.py) |
| `artifacts(run_id)` | `GET` `f"/runs/{quote(run_id, safe='')}/artifacts"` | [Contract/errors](https://docs.hexagon.autos/en/reference/artifacts-previews.md) · [Example](https://docs.hexagon.autos/en/build/artifacts.md) |
| `download_artifact(artifact_id)` | `GET` `f"/artifacts/{quote(artifact_id, safe='')}/content"`; bytes | [Contract/errors](https://docs.hexagon.autos/en/reference/artifacts-previews.md) · [Example](https://docs.hexagon.autos/en/build/artifacts.md) |
| `stream(run_id, after='0')` | `GET` `f"/runs/{quote(run_id, safe='')}/stream?after={quote(str(after), safe='')}"`; generator\[dict] | [Contract/errors](https://docs.hexagon.autos/en/reference/runs.md) · [Example](https://docs.hexagon.autos/en/build/stream-events.md) |

Regenerate with `python3 tooling/generate-python-doc-index.py`. This extracts signatures and request mapping, not server schemas or authorization. `**definition`, `**changes`, `**package`, `**resolution` and `**configuration` forward JSON fields validated by the server. See [configuration](https://docs.hexagon.autos/en/reference/configuration.md), [limits](https://docs.hexagon.autos/en/reference/limits.md), and linked workflow guides below. A method's existence does not grant the caller management permission.

## Workflows and return handling

| Methods | Inputs / result use | Behavior guide |
| - | - | - |
| catalog, applications, preflight\_\* | Inspect returned capabilities, readiness and scoped verification; preflight returns SessionPreflight-shaped JSON | [Choose integrations](https://docs.hexagon.autos/en/integrations/choose.md) |
| create/validate/update/delete\_connection, connection\_dependencies | Provider-specific config plus credential/Secret reference; read validation/dependencies before enable/delete | [Connection lifecycle](https://docs.hexagon.autos/en/build/connection-lifecycle.md) |
| register\_harness / register\_harness\_package | OCI `image` versus source `files`; retain returned id/version/digest | [OCI](https://docs.hexagon.autos/en/integrations/harnesses/oci.md), [source package](https://docs.hexagon.autos/en/integrations/harnesses/source-package.md) |
| create/revise/copy/archive\_agent | Immutable revisions; expected\_revision protects edits | [Agent templates](https://docs.hexagon.autos/en/build/agent-templates.md) |
| create\_session, session, session\_initialization | Direct harness or saved Agent, connection IDs; persist returned id, inspect pinned snapshot | [First Session](https://docs.hexagon.autos/en/start/first-session.md) |
| upload | Mapping of relative path to bytes; client Base64-encodes each value | [Project context](https://docs.hexagon.autos/en/build/project-context.md) |
| submit, run, cancel | Persist exact input/origin/key and returned Run id; query terminal state | [Backend integration](https://docs.hexagon.autos/en/build/backend-integration.md) |
| stream, events | Cursor string; generator versus JSON events envelope | [Event streams](https://docs.hexagon.autos/en/build/stream-events.md) |
| approvals, decide, tool\_calls, deny\_tool\_authorization, resolve\_tool\_call | Approval boolean differs from account authorization; use original call/hash for reconciliation | [Approvals](https://docs.hexagon.autos/en/build/approvals.md), [recovery](https://docs.hexagon.autos/en/build/recovery.md) |
| create\_preview, revoke\_preview, artifacts, download\_artifact | Preview grant is sensitive; download returns bytes | [Previews](https://docs.hexagon.autos/en/build/private-preview.md), [artifacts](https://docs.hexagon.autos/en/build/artifacts.md) |
| pause, resume, close, session\_activity | Lifecycle requests are not proof of provider cleanup; period accepts only 24h/7d | [Idle and wake](https://docs.hexagon.autos/en/build/idle-and-wake.md) |
| Secret, access, OAuth and Token methods | Sensitive management operations; preserve tenant boundaries and do not log returned credentials/grants | [Access control](https://docs.hexagon.autos/en/operate/access-control.md), [credentials](https://docs.hexagon.autos/en/operate/credentials.md) |
| deployment, update\_deployment, retry\_ingress, resource\_operation\* | Revision checks and persisted resource investigation; review does not prove absence | [CLI/configuration](https://docs.hexagon.autos/en/reference/configuration.md), [reconciliation](https://docs.hexagon.autos/en/operate/reconciliation.md) |

## Minimal contextual call sequence

This excerpt requires an initialized client, ready connection IDs, an application-saved key and persistence callbacks. It is not a complete cleanup-safe executable; use the [full program](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/first-session.py) for that workflow.

```python theme={null}
session = client.create_session(
    harness={'id': 'pi', 'version': '1.5.2'},
    sandbox_connection_id=sandbox_id, model_connection_id=model_id,
)
save_session_id(session['id'])
client.upload(session['id'], {'README.txt': b'Project context\n'})
run = client.submit(session['id'], saved_input, saved_key,
                    origin={'request_id': business_request_id})
save_run_id(run['id'])
for event in client.stream(run['id'], saved_cursor or '0'):
    if event.get('id'):
        store_event_and_cursor_atomically(run['id'], event)
result = client.run(run['id'])
```

Save the creation intent before creating; Session creation does not inherit Run idempotency. Reopen interrupted streams using the committed cursor. Query final status after streaming. Authorization/approval waits need the corresponding user flow; do not blindly approve everything in an event handler. Keep failure journals until resources are reconciled.

## Types, errors and coverage limits

`SessionPreflight` is imported by `hexagon`; supporting TypedDict definitions live in [contracts.py](https://github.com/NexusFox88/docs/blob/main/resources/sdk/python/hexagon/contracts.py). They describe JSON shape and do not validate runtime data or convert dicts into objects. Most methods have no annotated response type; do not infer a richer typed API.

HTTP errors become `HexagonError(status, code)` with `http_error` fallback. Network errors, timeouts, JSON decoding and local discovery failures may be different exceptions. `stream` raises ConnectionError on truncated/unexpected EOF and returns normally on `stream.end`; there is no infinite reconnect loop. `session_activity` rejects invalid periods locally with ValueError. See [errors](https://docs.hexagon.autos/en/reference/errors.md) before retrying.

`request(method, path, body=None, headers=None)` is the JSON escape hatch for implemented routes without convenience methods, such as listing one Session's Runs. It prepends `/v1`; it does not invent routes or bypass permissions. Browser preview transport, credential proxy traffic and OAuth browser redirects are not generic JSON SDK operations. The SDK has no full HTTP-schema model layer or built-in durable application journal.

The source-derived inventory, linked example callsites and return/error contract mapping have been reviewed for every public method. Linked examples share setup and normative HTTP contracts; their presence is not proof that every operation has been executed. Installed-package tests and cloud journeys retain their recorded scope and date. See [testing](https://docs.hexagon.autos/en/contribute/testing.md) for the distinction between source, type, deterministic and cloud evidence.

## Managed Secret and application Token calls

These independent helpers require an initialized **owner** client. Defining them makes no request; call only the operation you intend. Supply same-tenant resource IDs from your private management record and values from your credential storage. The snippets propagate errors and do not retry writes. TypeScript snippets use the `Hexagon` import shown above.

### Store and inspect provider credentials

```python theme={null}
def inspect_secrets(client, secret_id):
    metadata = client.list_secrets()['secrets']
    detail = client.secret(secret_id)
    return metadata, detail


def create_managed_secret(client, name, value):
    created = client.create_secret(name=name, value=value)
    return {'id': created['id'], 'version': created['version']}


def replace_managed_secret_value(client, secret_id, new_value):
    changed = client.update_secret(secret_id, value=new_value)
    return {'id': changed['id'], 'version': changed['version']}


def delete_unused_managed_secret(client, secret_id):
    # Server rechecks dependencies; a preceding GET cannot reserve deletion.
    client.delete_secret(secret_id)  # HTTP 204 -> None
```

`inspect_secrets` / `inspectSecrets` returns metadata and dependency information, never the stored value. Its Session dependency array is bounded and is not a full historical audit. Creation returns an ID/version to persist; a name is not a deduplication key.

Value replacement invalidates referencing connections: they become disabled and draft and require validation before explicit enablement. The returned Secret version is an observation, not an optimistic-lock condition. Do not call this helper again automatically after a timeout: inspect the original Secret and connection state first. Deletion can fail with `secret_in_use`; disabled connections still count as references. Successful deletion returns no JSON. None of these operations revokes a credential at the external provider. See the [full Secret contract](https://docs.hexagon.autos/en/reference/secrets.md).

### Issue, rotate and revoke backend credentials

```python theme={null}
def application_token_metadata(client):
    return [row for row in client.list_tokens()['tokens']
            if row['role'] == 'application']


def issue_application_token(client, label):
    return client.create_token(label, expires_in_days=30)


def rotate_application_token(client, old_token_id):
    return client.rotate_token(old_token_id)


def revoke_application_token(client, token_id):
    receipt = client.revoke_token(token_id)
    return {'id': receipt['id'], 'revoked_at': receipt['revoked_at']}
```

The create and rotate helpers return **plaintext-bearing objects** with `id`, `token`, `label`, `role`, `expires_at` and `created_at`. Immediately transfer `token` to your backend's secret store and preserve its ID in private management records. Do not print these objects, return them to a browser, or include them in exception diagnostics. If saving to your secret store fails, preserve the receipt privately and reconcile that issued credential; rerunning the helper creates another operation and cannot recover the first plaintext.

Metadata listing includes expired and revoked application rows; the role filter does not make them active. Rotation returns a **new ID**, invalidates the old token immediately and preserves its original expiry. There is no overlap window, and replaying the old rotation cannot retrieve the replacement. Revocation returns JSON with `revoked_at`, unlike Secret deletion's empty response. It tolerates repeated revocation of the same application row and does not cancel already accepted Runs.

Before invoking a write, record the intended operation and target privately. A lost create/rotate response requires investigation using metadata; names and labels alone cannot identify a unique result. Use the [Token contract](https://docs.hexagon.autos/en/reference/tokens.md) for response-loss recovery and the [identity operations guide](https://docs.hexagon.autos/en/operate/access-control.md) for deployment and credential verification. These examples describe SDK calls; syntax/type checking does not verify live credential creation, external provider revocation or a complete rotation rollout.

## Connection lifecycle calls

Use these independent helpers with an initialized owner client; defining them does not create or mutate connections. The Vercel creation example requires an actual project/team pair and a Token from private credential storage. Record the creation intent before calling, and persist the returned connection ID before a later validation step. [Vercel configuration](https://docs.hexagon.autos/en/integrations/sandboxes/vercel.md) defines the provider-specific requirements; substitute another provider's full definition only after reading its guide.

```python theme={null}
def inspect_connection(client, connection_id):
    return {
        'catalog': client.list_connections()['connections'],
        'connection': client.connection(connection_id),
        'dependencies': client.connection_dependencies(connection_id),
    }


def create_vercel_connection(client, project_id, team_id, token):
    created = client.create_connection(
        kind='sandbox', provider='vercel', name='Vercel workspace',
        credential=token,
        config={'project_id': project_id, 'team_id': team_id, 'vcpus': 2},
    )
    return created['id']


def validate_and_enable_connection(client, connection_id):
    checked = client.validate_connection(connection_id)
    if checked['status'] != 'ready':
        return {'enabled': False, 'stage': 'validation',
                'code': (checked.get('validation') or {}).get('code')}
    enabled = client.update_connection(connection_id, enabled=True)
    return {'enabled': enabled['enabled'], 'stage': 'enable',
            'status': enabled['status'], 'version': enabled['version']}


def disable_connection(client, connection_id):
    changed = client.update_connection(connection_id, enabled=False)
    return {'id': changed['id'], 'enabled': changed['enabled']}


def delete_unused_connection(client, connection_id):
    client.delete_connection(connection_id)  # HTTP 204 -> None


def discover_remote_mcp(client, connection_id):
    discovered = client.discover_mcp_tools(connection_id)
    return {'id': discovered['id'], 'version': discovered['version'],
            'status': discovered['status'], 'enabled': discovered['enabled']}


def disconnect_tool_credentials(client, connection_id):
    disconnected = client.disconnect_connection(connection_id)
    return {'id': disconnected['id'], 'enabled': disconnected['enabled'],
            'provider_revoked': disconnected['provider_revoked']}
```

Choose the helper for the current stage; do not run the entire block as a create/discover/disconnect/delete sequence:

| Stage | Result to inspect and next action |
| - | - |
| Inspect | Returns connection metadata plus a dependency sample. Reads are separate observations, not a transaction or deletion reservation. Dependency arrays are capped at 100 each; an empty list is not a client-side deletion authorization. |
| Create | Returns one connection ID; it is not yet validated or enabled. Repeating creation can create another row, even with the same name. |
| Validate and enable | HTTP success with `status: invalid` returns `enabled: false` from the helper and does not attempt enablement. Only ready verification proceeds to a separate enable PATCH. Inspect the final returned state. |
| Disable | Prevents eligible new work but does not cancel every in-flight call, change pinned Session definitions or delete cloud resources. |
| Delete | Invoke after settling work and confirming dependent Sessions closed. The server independently checks dependencies; `connection_in_use` is an error, not a reason to delete records manually. Success has no JSON body. |
| Discover MCP | Only for a `tool` / `mcp-remote` connection. Discovery revises selected tools and leaves the connection draft and disabled. Inspect the new config privately, then validate and explicitly enable it. |
| Disconnect Tool | Only for Tool connections. Clears local credential linkage and pending OAuth flows. `provider_revoked: false` means the external account was not revoked; this does not delete a shared Secret. |

Validation can contact providers, refresh OAuth credentials and incur model usage. A concurrent configuration change can yield `connection_changed_during_validation`; reread the connection and review the intended config before another attempt. The validation/enable pair is not one atomic request, and there is no client-side compare-and-set guard. Coordinate management changes in your application.

Updating `config` replaces the whole config object. Credential/config changes reset readiness, so do not combine them with `enabled: true`. Even repeated disablement, disconnect or an empty PATCH can advance versions. The snippets propagate HTTP/network errors without retrying; after a lost response, inspect the original ID and state. The inspect helper may return private account metadata and is not a logging payload.

See [connection response contracts](https://docs.hexagon.autos/en/reference/connections.md) for exact fields/errors, [connection changes](https://docs.hexagon.autos/en/build/connection-lifecycle.md) for existing Session handling, and [OAuth](https://docs.hexagon.autos/en/reference/oauth.md) for consent. These examples have local syntax/type verification, not fresh provider-validation or cloud-execution evidence.

## Catalogs and OAuth consent calls

These helpers require an initialized owner client. Catalog reads let you inspect advertised integrations and application operation requirements; they do not validate your account or prove an execution combination. Select an OAuth-capable application, create its Tool connection with the intended operations, and use the provider's registered client ID/secret and matching callback URL. The callback path must be `/oauth/callback`; see [OAuth configuration constraints](https://docs.hexagon.autos/en/reference/oauth.md).

```python theme={null}
def read_integration_catalogs(client):
    return {'execution': client.catalog(), 'applications': client.applications()}


def configure_oauth_client(client, provider, client_id, client_secret, redirect_uri):
    return client.configure_application_oauth(
        provider, client_id=client_id, client_secret=client_secret,
        redirect_uri=redirect_uri,
    )


def begin_consent(client, connection_id):
    flow = client.authorize_connection(connection_id)
    return {'id': flow['id'], 'authorization_url': flow['authorization_url'],
            'expires_in': flow['expires_in']}


def inspect_consent(client, connection_id, flow_id):
    flow = client.authorization_flow(flow_id)
    if flow['connection_id'] != connection_id:
        raise ValueError('Authorization flow belongs to a different connection')
    result = {'flow': flow}
    if flow['status'] == 'completed':
        result['authorization'] = client.connection_authorization(connection_id)
    return result


def cancel_pending_consent(client, flow_id):
    return client.cancel_authorization(flow_id)
```

Call these helpers as separate stages of your backend's consent flow:

1. Configure the OAuth client when setting up or deliberately changing the integration. Do not repeat configuration for every status poll: changing it can invalidate in-flight flows. The returned `{configured, provider, client_id, redirect_uri}` confirms configuration only, not user consent.
2. Begin consent once, persist the returned flow ID and its connection/business-user association privately, then present `authorization_url` only to the intended user. This URL contains flow state; do not log it or send the owner token to the browser. The user completes consent on the provider's page. The SDK does not automate that interaction.
3. Query the saved flow ID with `inspect_consent` / `inspectConsent`. Each call makes one flow read, plus one authorization-state read only after completion. Schedule bounded polling in your application; these helpers do not sleep, loop or start another flow. A browser redirect alone is not success.
4. If the user abandons consent, call the cancel helper for that saved flow. It returns a flow object, not an empty response. Cancellation only changes a pending flow; if the callback completed first, the response can remain completed.

| Flow result | Application action |
| - | - |
| `pending` | Continue observing the same flow within its deadline; do not repeatedly start consent. |
| `completed` | Inspect the returned authorization state and current connection readiness. Completion is historical: later revocation or configuration changes may already require reauthorization. |
| `failed` | Read `error_code`, explain the failed attempt and repair its cause before a deliberate new consent attempt. |
| `cancelled` / `expired` | Stop polling this attempt. Start another only when the user intends to authorize again. |
| Unknown state or mismatched connection | Do not declare success. Preserve the original IDs and investigate; the helper rejects a connection mismatch before querying authorization. |

Connection authorization uses its own `state` values (`oauth`, `manual`, `disconnected`, `reauthorization_required`, `refreshing`, `refresh_unknown`), not flow `status`. `oauth` and `refresh_available` describe stored lifecycle facts; the read does not refresh a token or check live provider revocation. Unknown refresh outcomes require investigation or deliberate reauthorization, not replaying a possibly rotated refresh token.

Starting consent again cancels pending flows for that connection. A lost start response is therefore not safely recovered by blindly calling the start helper again; preserve the uncertainty and deliberately replace the attempt only when appropriate. Cancelling a flow does not revoke existing provider credentials, cancel a Run or decide a Tool approval. `app_oauth_setup_required`, `app_oauth_unsupported`, `app_oauth_flow_not_found` and authentication errors propagate through the SDK; network failures remain distinct. See [OAuth responses and errors](https://docs.hexagon.autos/en/reference/oauth.md) and [application integration](https://docs.hexagon.autos/en/integrations/apps.md).

These functions are contextual SDK examples with caller-supplied credentials and IDs. Local code checks do not establish browser consent, token exchange or provider account verification.

Agent list/read, preflight, revision, copy, archive and pinned-initialization examples are in [prepare and apply a template revision](https://docs.hexagon.autos/en/build/agent-templates.md). The examples preserve the observed revision and explain environment preservation and lost-response recovery.

For six contextual Session environment/authorization and access-grant methods, see [SDK access examples](https://docs.hexagon.autos/en/reference/session-access.md). The examples separate plaintext reads, token issuance, one-grant revocation and Session binding revocation.

Operational SDK examples cover [overview, Session/pending pages, activity and health](https://docs.hexagon.autos/en/reference/monitoring.md), and [deployment revision updates plus ingress retry/stop](https://docs.hexagon.autos/en/reference/deployment.md). These keep observation, saved configuration and running-process actions separate.

Explicit [pause/resume examples](https://docs.hexagon.autos/en/build/idle-and-wake.md) and [verified Tool resolution](https://docs.hexagon.autos/en/reference/approvals-tools.md) cover lifecycle intent, partial response loss and exact-body reconciliation replay.

## Response contracts by resource

The generated signatures show how to invoke the client. Use the corresponding HTTP contract for exact response projections, status codes, required role, state preconditions and effects. Most management methods return the decoded JSON directly; a successful promise/call can still carry invalid connection validation or reconciliation\_error. Do not infer success from the absence of an SDK exception.

| Resource | Contract |
| - | - |
| Runs, events and cancellation | [Runs, events and cancellation](https://docs.hexagon.autos/en/reference/runs.md) |
| Session creation, files and lifecycle | [Session creation, files and lifecycle](https://docs.hexagon.autos/en/reference/sessions.md) |
| Session environment, authorization and grants | [Session environment, authorization and grants](https://docs.hexagon.autos/en/reference/session-access.md) |
| Artifact bytes and private previews | [Artifact bytes and private previews](https://docs.hexagon.autos/en/reference/artifacts-previews.md) |
| Approvals and Tool recovery | [Approvals and Tool recovery](https://docs.hexagon.autos/en/reference/approvals-tools.md) |
| Connections, validation and usage | [Connections, validation and usage](https://docs.hexagon.autos/en/reference/connections.md) |
| Applications and OAuth | [Applications and OAuth](https://docs.hexagon.autos/en/reference/oauth.md) |
| Managed Secrets | [Managed Secrets](https://docs.hexagon.autos/en/reference/secrets.md) |
| Application tokens | [Application tokens](https://docs.hexagon.autos/en/reference/tokens.md) |
| Agent templates and revisions | [Agent templates and revisions](https://docs.hexagon.autos/en/reference/agents.md) |
| Catalog and Harness registration | [Catalog and Harness registration](https://docs.hexagon.autos/en/reference/harness-registration.md) |
| Resource operation reconciliation | [Resource operation reconciliation](https://docs.hexagon.autos/en/reference/resource-operations.md) |
| Monitoring and collection queries | [Monitoring and collection queries](https://docs.hexagon.autos/en/reference/monitoring.md) |
| Local deployment configuration | [Local deployment configuration](https://docs.hexagon.autos/en/reference/deployment.md) |

Binary artifact download and streaming are special return paths described above. HTTP DELETE is not uniformly empty: Token revoke returns JSON, while preview/access/Secret/connection deletion uses 204. OAuth flow cancellation returns a flow object. Preserve these differences when building a generic application wrapper.

## Inspect an existing Run without submitting work

With the `.venv` from this page activated and the checkout SDK installed, run the [complete diagnostic example](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/inspect-run.py) from the repository root. Replace both IDs with existing resources in the same tenant; `--help` checks the CLI entry without discovering a workspace or querying the API:

```sh theme={null}
python examples/documentation/inspect-run.py --help
python examples/documentation/inspect-run.py --session YOUR_SESSION_ID --run YOUR_RUN_ID --after 0 --max-pages 20
```

It checks the Run/Session association, queries Session state, reads up to the requested number of event pages, re-queries the Run and lists artifact IDs/sizes/digests. It excludes task text, event payloads, output text and artifact names from its report; IDs still belong in private evidence. It never submits, approves, cancels or closes work.

Event IDs stay decimal strings, with arbitrary-precision comparisons. `last_observed_cursor` is a diagnostic observation, not a persisted application-consumer checkpoint: the program counts events rather than storing their payloads. An empty page only means the query was drained at that moment. The later Run query and artifact listing are separate reads, so this is not an atomic snapshot. If the page bound is reached, continue with the reported cursor for diagnostics; do not discard unprocessed application events based on that cursor.

Local syntax and deterministic fake-client checks are separate from real API acceptance. Use [Run contracts](https://docs.hexagon.autos/en/reference/runs.md) and [recovery](https://docs.hexagon.autos/en/build/recovery.md) to interpret the result.

[Example setup, stages and recovery](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/README.md).

## Porting between the two SDKs

| Concern | Python | TypeScript |
| - | - | - |
| Client creation | `Hexagon.local()` returns the client synchronously | `await Hexagon.local()` |
| HTTP calls | Blocking calls; do not invoke directly in an async server event loop | Promises; await each dependent operation |
| Upload input | `{relative_path: bytes}`; SDK encodes Base64 | Array of `{path, content_base64}`; caller encodes bytes |
| Streaming | Synchronous generator; use `for`; close a retained generator after partial consumption | AsyncGenerator; use `for await`; optional AbortSignal ends observation |
| Download | `bytes` | `Uint8Array` |
| HTTP 204 | `None` | `undefined` |
| Event cursor | Numeric string; `int` can compare without precision loss | Numeric string; use `BigInt`, not `Number` |
| Optional query fields | Omit unused keyword arguments; `None` can be serialized as text | Omit unused properties; explicit `undefined` can become text |
| Pagination | Caller follows response envelope | Caller follows response envelope |

Neither SDK automatically retries writes or persists recovery state. Switching language does not change tenant permissions, resource ownership or the identity of an existing Session. Keep the same input, origin and key when recovering one submission across clients.

## Read bounded pages of Run summaries

This helper requires an initialized trusted-backend client. It calls the tenant-wide summary endpoint, not the per-Session Run list. A non-null returned `next_offset` means the page budget stopped collection before the observed end. Errors propagate to the caller; the function makes no write request.

```python theme={null}
def read_run_summary_pages(client, *, max_pages=10):
    if not isinstance(max_pages, int) or isinstance(max_pages, bool) or max_pages < 1:
        raise ValueError("max_pages must be a positive integer")
    rows, offset = [], 0
    for _ in range(max_pages):
        page = client.list_runs(limit=100, offset=offset)
        rows.extend(page["runs"])
        next_offset = page["next_offset"]
        if next_offset is None:
            return {"runs": rows, "next_offset": None}
        if not isinstance(next_offset, int) or isinstance(next_offset, bool) or next_offset <= offset:
            raise ValueError("invalid pagination progress")
        offset = next_offset
    return {"runs": rows, "next_offset": offset}
```

`runs` here contains summaries, so fetch `client.run(id)` (with `await` in TypeScript) when full input/output is needed. Concurrent inserts can shift offsets; this helper does not provide a stable export or certify that every Run was seen. A returned next offset is a continuation hint, not a durable event cursor. For event replay, use the original Run ID and event `after` contract instead. See [collection semantics](https://docs.hexagon.autos/en/reference/runs.md) and the [bounded diagnostic example](https://github.com/NexusFox88/docs/blob/main/resources/examples/documentation/README.md).

Continue with the [complete first Session](https://docs.hexagon.autos/en/start/first-session.md), [backend integration](https://docs.hexagon.autos/en/build/backend-integration.md), or [event/state reference](https://docs.hexagon.autos/en/reference/events-and-states.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.