Skip to main content
@hexagon/agent-sdk is an ESM package, currently version 0.1.0, with Node.js >=20 in its package manifest. The control-plane repository separately requires Node.js >=22.19.0. Do not infer browser or edge-runtime support from the Node package requirement. Local identity discovery imports Node filesystem/path/OS modules and belongs in a trusted backend. Build from this checkout, then install it into your own Node application:
The absolute path is a placeholder. This does not claim public npm publication. See package.json; record the artifact and source revision as well as version.

Install a packaged snapshot

To test the files that an independent application receives, build and pack a local tarball. Run these commands from the Hexagon repository root; replace the destination and application paths with directories you own:
The last command should print function. Use the filename printed by npm pack if the version changes. --ignore-scripts skips the package’s prepack build, so the explicit build must succeed first. Packing writes a local archive; it does not publish to npm. Keep the archive with the source revision for reproducibility. The package exports ESM and TypeScript declarations from dist; a CommonJS require entry is not declared. The local tarball path has been checked by installing into a temporary application outside the checkout. A loopback simulated HTTP service verified authenticated Run retrieval, a decimal event cursor above JavaScript’s safe integer range, and HexagonError status/code conversion. This proves package consumption and those client behaviors, not actual server authorization or cloud execution. See the installation evidence.

Initialize a client

The explicit base URL excludes /v1, which the SDK appends. Construction makes no validation request. local({dataDirectory, baseUrl}) returns a Promise and verifies private workspace files/loopback identity; optional baseUrl checks the discovered endpoint, rather than switching to hosted authentication. See local.ts. Never embed control-plane Tokens in frontend bundles. Authenticate business users in your backend and forward authorized results. The SDK does not have a client-wide dispose method; close(session) requests Session closure. Breaking out of stream iteration releases its reader but does not cancel execution.

Public methods and actual return types

This inventory is generated with the installed TypeScript compiler from the source declarations and inferred return types. Initializers show real defaults; Promise<any> is preserved rather than replaced with an invented response model. JSON responses are not runtime-validated by these types. Generic request returns undefined for HTTP 204 even when a caller supplies an incompatible generic type. Regenerate using node tooling/generate-typescript-doc-index.mjs. Server schemas still validate unknown, input objects and query values. Optional query fields should be omitted rather than explicitly set to undefined: list methods stringify supplied entries. Pagination is explicit; events and artifacts retain their collection envelopes.

Exported types

Definitions live in index.ts. LocalOptions is declared in local.ts; the package exports map exposes the root entry, not a promised public local subpath import.

Where declarations are narrower or wider than the HTTP contract

Server validation still applies when TypeScript accepts an object. Conversely, an omitted response field in a declaration does not mean the server discarded it. Keep runtime validation separate from type assertions; neither changes permissions or retry semantics.

Common calls with context

The following excerpt requires an initialized client, ready connection IDs, saved submission intent and application-owned persistence functions. It does not include the complete recovery/cleanup path; use the full first-Session program for that.
Unlike Python upload, TypeScript upload accepts an array containing already encoded Base64 strings. Keep Session/Run IDs and exact input/origin/key in your application journal. A lost submission response can be recovered with the same intent; Session creation has no equivalent Run-submission idempotency guarantee. Use backend integration and project context.

Streams, cancellation and errors

stream(run, after='0', signal?) is an AsyncGenerator. Iterate with for await, checkpoint only durable event IDs, and reconnect to the original Run after the last committed cursor. IDs stay strings. stream.end has no durable ID; query the Run afterward. Unexpected EOF/truncated data throws an ordinary Error; reconnect is not automatic. An AbortSignal passed to stream stops local observation. It does not cancel the Run. cancel(run) requests execution cancellation; close(session) separately handles resource cleanup. Not every convenience method accepts a signal. Generic request accepts one as its fifth argument; it provides no universal request timeout by default. Supply a signal where supported and handle unknown operation outcomes correctly. Ordinary JSON request errors become HexagonError with server code or http_error; stream-open errors use event_stream_failed, and artifact download fallback is artifact_download_failed. Fetch/abort/JSON errors may remain native exceptions. Generic request rejects redirects, while the stream/download paths use fetch’s default redirect behavior. Use the actual trusted API origin and do not rely on redirects. See errors.

Management workflows and gaps

Use connections for CRUD and validation; applications and MCP for operation selection; Agent templates for revisions; approvals and reconciliation for decisions. Secret, Token, OAuth and deployment methods require the appropriate management role. Their presence in the class does not authorize the caller. Keep grants and returned credentials out of logs. Generic request<T>(method, path, ...) can reach implemented JSON endpoints without a convenience method, such as a Session-scoped Run list. It cannot invent endpoints, perform browser OAuth interaction or proxy arbitrary binary responses. The generic type parameter is a compile-time assertion, not a schema check. There is no built-in durable journal, universal pagination loop or safe automatic retry for side effects. 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

Build the SDK, then run the complete diagnostic example from the repository root:
It checks Run/Session association, reads bounded event pages, queries current Run state and lists artifact IDs/sizes/digests. It omits task/event/output content and artifact names; resource IDs still require private handling. It never submits, approves, cancels or closes work. Decimal-string cursors use BigInt comparisons rather than lossy JavaScript numbers. last_observed_cursor is diagnostic, not an application-consumer checkpoint: this program counts events instead of persistently storing their payloads. reached_empty_event_page describes one query, not Run completion. Separate state/event/artifact reads are not an atomic snapshot. Continue diagnostics from that cursor when bounded, but do not use it to skip unprocessed application events. Type checking and fake-client checks do not certify real API or cloud behavior. See Run contracts and recovery. 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.