Skip to main content
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:
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.

Client and identity

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. 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. 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, limits, and linked workflow guides below. A method’s existence does not grant the caller management permission.

Workflows and return handling

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 for that workflow.
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. 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 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 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

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.

Issue, rotate and revoke backend credentials

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 for response-loss recovery and the identity operations guide 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 defines the provider-specific requirements; substitute another provider’s full definition only after reading its guide.
Choose the helper for the current stage; do not run the entire block as a create/discover/disconnect/delete sequence: 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 for exact fields/errors, connection changes for existing Session handling, and OAuth for consent. These examples have local syntax/type verification, not fresh provider-validation or cloud-execution evidence. 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.
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.
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 and application integration. 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. 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. 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, and deployment revision updates plus ingress retry/stop. These keep observation, saved configuration and running-process actions separate. Explicit pause/resume examples and verified Tool resolution 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. 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 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:
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 and recovery to interpret the result. Example setup, stages and recovery.

Porting between the two SDKs

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.
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 and the bounded diagnostic example. Continue with the complete first Session, backend integration, or event/state reference.