Assign responsibilities before sending requests
Your backend decides whether a business user may use a task, Session, Run or artifact. Hexagon validates its tenant boundary and manages execution. These checks complement each other: an application Token shared by Alice and Bob cannot tell Hexagon which business user’s records your endpoint should expose. Check the application ownership relation before both mutations and reads, including event subscriptions and download proxies. Keep the Hexagon Token in the backend; return your own authorized response to the browser.Persist the relationships
The following is a suggested application model, not Hexagon’s database schema:
A well-formed Session ID is not authorization. Resolve its ownership through your business database before contacting Hexagon. This remains necessary when multiple business users share one control-plane tenant.
Initialize the client
Use local discovery for local development. For a remote control plane, configure the URL and an appropriate application Token on the backend.Create context and submit work
Create a direct Session for the business context:saved* values come from a committed submission intent, not fresh values generated on every HTTP retry. origin helps correlate requests; it does not replace authorization or idempotency. The request hash includes input and nonempty origin. Changing either while reusing a key produces idempotency_conflict.
Your database and Hexagon do not share a transaction. Handle the gap where a remote request succeeds before its response is saved: persist intent, send, then persist the response. Recover lost Run submission responses by resending the same Session, input, origin, and key.
Session creation does not have that Run idempotency contract. An unknown creation outcome requires investigation through Session queries or Console before creating another. Track such records in an observable recovery queue rather than repeatedly creating resources.
Normal submission and lost-response recovery
The diagrams start after the application has persisted an authorized Session association.request-001 identifies one business intent; pressing “continue” with a new task creates a new intent and key.
A timeout is not proof that the Run was rejected. With a saved Run ID, query it; without one, recover the committed Run submission as shown. A changed payload with the old key is an intent conflict, not permission to manufacture a new key. A new key represents new work and can create another Run after the original finishes. This recovery does not authorize blindly repeating Session creation, Tool side effects or unknown cloud-resource operations.
Runnable durable-submission example
backend-intents.py uses application-owned SQLite for context ownership, business requests, exact input/origin, idempotency keys and Run IDs. Database operations and Hexagon SDK calls are separate, making restart and lost-response boundaries observable. Install the Python SDK first and use an existing, authorized Session that can accept work; do not reuse the first tutorial’s already closed Session. Each command runs in a separate process. Store the database and input file in a private directory and replace YOUR_SESSION_ID with the backend-confirmed Session:Query and deliver results
Query saved Run IDs withclient.run(run_id) in Python or await client.run(runId) in TypeScript. Distinguish queued, executing, waiting for authorization/approval, and terminal states in the UI.
Subscribe and forward events from the backend. Frontend disconnection means observation stopped; it must not automatically cancel execution. Confirm terminal state through durable queries. Recheck business ownership before delivering artifacts. Preview URLs are expiring access credentials and should not enter public logs.
Deliver an artifact through an authorized application endpoint
The SQLite example also exposesstore.deliver_artifact(client, user, request, artifact_id) as a library method. Your HTTP handler supplies user from its authenticated session, resolves the business request and calls this method before writing the download response. It returns verified bytes; the CLI intentionally does not print them.
The method checks business ownership before remote calls, verifies that the saved Run still belongs to the saved Session, requires a terminal state, finds the requested artifact in that Run’s export list, checks its Run/Session association, and verifies byte count and SHA-256. It never uses an exported name as a local path. Failed or cancelled Runs can have useful artifacts: the method permits their verified exports, while your UI must still show the actual Run outcome and apply the business task’s success criteria.
An active Run is rejected by this example’s delivery policy, although the underlying API can list exports during execution. Keep progress events separate from settled-result delivery. An unknown artifact, wrong association or integrity failure must not become a successful empty download. Map these failures to your application’s response contract and retain enough private context for diagnosis.
Return bytes as an attachment using an application-chosen safe filename and application/octet-stream; do not render generated HTML on your application origin. Recheck the authenticated user on each download and event-subscription request. If your product supports sharing or ownership transfers, implement that authorization policy explicitly rather than treating possession of a Run/artifact ID as permission.
The delivery check record uses real temporary SQLite and a fake SDK. It checks restart-safe delivery, cross-user and unrelated-artifact denial, wrong remote associations, active-Run refusal and corrupted bytes, alongside submission recovery. It does not implement login, a production HTTP download endpoint, streaming large responses or the equivalent TypeScript database integration.
Handle concurrency and cleanup
Only one Run can be active per Session. Onsession_busy, your application can retain a message and submit it after the current Run terminates. This is an application queue, not an automatic platform queue. Use separate Sessions for independent work within account limits.
Assign an explicit close policy to every Session. Settle active work, request closure, and record the confirmed outcome. Process exit hooks are insufficient: unfinished cleanup must survive restarts in your database.
Persist and recover a close intent
The runnable example stores cleanup separately from submissions. After deciding that a context should close, use its existing authorized Session ID:request-cleanup commits a requested record without contacting Hexagon. It prevents subsequent prepare/new-submit calls through this store; reads of already saved Runs and verified artifact delivery remain available. Repeating the command preserves the existing record, including confirmed status.
cleanup-step queries the same Session first. If already closed, it records confirmed without sending close again. Otherwise it sends one close request, then queries again; it confirms only when the read reports closed. An error leaves the durable intent in place and records only the exception class, not potentially sensitive exception text. After investigating the error, rerun the same command for that Session. There is no automatic retry loop or direct Provider deletion.
This command is an observable cleanup step, not a background scheduler. A production worker needs bounded backoff, monitoring and ownership of each pending record. Serialize submission admission and close intent across workers; the example’s local check is not a distributed lock and cannot eliminate races with already in-flight submissions. Hexagon’s active-Run check remains necessary.
The cleanup example checks use real SQLite and a fake SDK to verify restart persistence, blocking subsequent new work, lost-close-response recovery, failure retention and cross-user denial. They do not establish real cloud deletion or a concurrent production scheduler. Keep your application cleanup record alongside the control plane’s resource-operation evidence.