BlogTangle Network Protocolpart 8 of 10
Deploy a Paid AI Agent Service: One Traceable Job
A practical path for exposing one paid AI job with discovery, authorization, payment, execution, recovery, and evidence that a buyer can inspect.
This post is about the Tangle Network protocol, a separate project from Tangle's infrastructure for AI agents. Introduction to Tangle covers the agent infrastructure.
A buyer sends a paid request to an AI service. The network connection times out after the wallet signs the payment, so the buyer cannot tell whether the service received the request, settled the payment, started the job, or returned a result. Retrying blindly could charge twice. Waiting forever could hide a failed job.
Deploying a paid AI agent service means designing those states before publishing the endpoint.
This guide uses Tangle’s service-definition and payment surfaces because they make the boundary visible. For account billing or a subscription, map the same boundaries to invoice status, account authorization, Job admission, and result delivery.
The Sandbox SDK carries this argument. client.instances.ensure({ key: "customer:…", profile, create }) keeps one sandbox per customer key, and instance.turn(ask, { thread, turnId }) starts or reads a turn whose state moves from running to completed. A buyer therefore sees a job’s progress through the turn state, not one opaque response. A one-shot client.run reports run.usage (input and output tokens) and run.costUsd (model spend).
Define an inspectable Job first
An agent service is an API that accepts a task for an AI system and returns a result or artifact. Choose a first task whose input and output can be described without a conversation. For example, a service might accept a public document URL and return a classification, extracted fields, citations, and a list of unresolved questions.
The buyer should not have to trust the service’s prose to know whether it completed.
| Boundary | First version |
|---|---|
| Input | One documented JSON shape with size and content limits |
| Price | One fixed price or one short, explicit price table |
| Authorization | Public paid access or one named caller rule |
| Execution | One agent workflow or deterministic service function |
| Output | One result or artifact with a check a buyer can run or inspect |
| Retry | A caller-owned request ID and documented replay behavior |
| Support | A job ID, payment record, and trace ID returned or recoverable |
A Blueprint is a reusable service template that defines executable artifacts, jobs, inputs, outputs, metadata, and optional protocol rules. A Service is a live instance created from that Blueprint. A Job is one callable unit inside the Service. An operator is the person or team running the Service and returning Job results. The Blueprint introduction describes those objects and the roles around them.
Separate the buyer’s states
Payment and work are different state machines.
Put them in one trace, but do not collapse them into one boolean called success.
| State | Meaning | Evidence the service should retain |
|---|---|---|
discovered |
The buyer found the product and job contract | Manifest, docs, package or endpoint, and schema |
priced |
The service returned current payment requirements | Price response, currency or token, network, expiry, and job identity |
challenged |
The service refused an unpaid request with payment requirements | HTTP status, payment header or body, and request ID |
verified |
The payment payload passed the configured checks | Verification response and quote or payment digest |
settled |
The payment was submitted or confirmed according to the payment path | Settlement identifier and network result |
accepted |
The paid request was admitted to the job queue | Job ID, call ID, and queue status |
running |
The service has started execution | Start time, operator, model or tool route, and trace ID |
completed or failed |
The job returned a result or an execution error | Artifact, result status, error category, and end time |
reviewed or disputed |
The buyer or an automated check accepted or challenged the result | Acceptance check, evidence links, and support decision |
The distinction protects both sides. A buyer can receive a settlement receipt and still need a refund when the job fails. An operator can show that a job completed and still need to investigate a quality dispute.
How x402 turns an HTTP request into a paid job
x402 is an open protocol that uses the reserved HTTP 402 Payment Required status to communicate payment requirements over a normal request-response flow.
The client sends a request, the server returns the requirements, the client creates a signed payment payload, and the client retries the same request with payment proof.
The official x402 flow describes verification, settlement, and resource delivery as separate steps.
A facilitator is a service that verifies a payment payload and can submit the settlement transaction for the server. The facilitator documentation explains that the facilitator can reduce the server’s blockchain integration work while leaving the signed payment tied to the buyer’s wallet. The operator still needs a policy for what happens when verification succeeds but settlement or execution fails.
Tangle’s Blueprint SDK exposes x402 as an operator-run HTTP ingress path.
The gateway advertises payment requirements per job, verifies and settles through a facilitator, and injects a paid request into the Blueprint Runner, the process that dispatches Blueprint Jobs to their handlers.
A JobCall is the runner’s record of one request to a Blueprint Job; it identifies the queued call but not its eventual result.
The Tangle x402 documentation documents the gateway and its job producer.
This gateway is an optional off-chain payment path around the Blueprint runner; the HTTP exchange coordinates payment and job admission but does not make the job result an on-chain fact.
The public Tangle endpoints include:
GET /x402/health
GET /x402/stats
GET /x402/jobs/{service_id}/{job_index}/price
POST /x402/jobs/{service_id}/{job_index}
POST /x402/jobs/{service_id}/{job_index}/auth-dry-run
The price endpoint is discovery and does not require payment.
The paid job endpoint returns 402 when the request lacks valid payment proof.
After verification and settlement, Tangle documents a 202 Accepted response that means the paid request was enqueued and a JobCall was injected into the runner.
202 Accepted does not mean that the Job has completed.
The headers and body details depend on the x402 version and integration.
For an x402 v2 flow, payment requirements use PAYMENT-REQUIRED, the client retry carries PAYMENT-SIGNATURE, and a successful response can carry PAYMENT-RESPONSE settlement information.
Use the x402 migration guide and the Tangle gateway documentation together when implementing the boundary.
An illustrative exchange looks like this:
GET /x402/jobs/1/0/price HTTP/1.1
Host: service.example
HTTP/1.1 200 OK
Content-Type: application/json
{
"service_id": 1,
"job_index": 0,
"price_wei": "1000000000000",
"settlement_options": [{"network": "eip155:84532", "token": "USDC"}]
}
POST /x402/jobs/1/0 HTTP/1.1
Host: service.example
Content-Type: application/json
{"documentUrl":"https://example.com/report.pdf"}
HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: <encoded payment requirements>
POST /x402/jobs/1/0 HTTP/1.1
Host: service.example
Content-Type: application/json
PAYMENT-SIGNATURE: <signed payment payload>
{"documentUrl":"https://example.com/report.pdf"}
HTTP/1.1 202 Accepted
PAYMENT-RESPONSE: <settlement details>
{
"status": "accepted",
"receipt": "<quote digest>",
"service_id": 1,
"job_index": 0,
"call_id": 1
}
The values and encoding in this block are illustrative. The protocol and service version determine the exact fields.
Health comes before a payment challenge
A service should avoid presenting a price for work it already knows it cannot accept. The operator can check its own runtime, model route, queue capacity, facilitator reachability, and credential policy before exposing a paid job.
The Tangle x402 gateway documents /x402/health and /x402/stats for gateway health and lightweight counters.
Those endpoints help an operator identify accepted, denied, replay-denied, or enqueue-failed requests.
They do not establish that the model will return a correct answer.
If the job calls a model router, the router is the service that accepts a stable model-request format and chooses a provider or model route. The Tangle Router manifest exposes public health and model discovery calls. Record the selected route in the job trace because “the Router was healthy” and “this model call completed” are different facts.
Do not hide a dependency failure behind a generic payment error. Return a clear unavailable state or refuse new work before a buyer signs a payment when the product can know that the job cannot start.
Retries need a business rule
The server cannot infer from a timeout whether the first request was never received, was paid and queued, or completed before the response was lost.
The application needs a caller-owned request ID or idempotency key. An idempotent request can be repeated without creating a second business effect for the same logical operation. For an asynchronous AI job, the service can return the original job and result when the same request ID reappears. If the service cannot safely replay or return the original state, it should reject the ambiguous retry and give the buyer a support path.
Payment protocol replay protection and business idempotency are related but different. x402 implementations validate payment payloads and nonces according to their scheme. The service still owns the rule that decides whether two equal application requests create one Job or two.
In the Sandbox SDK, the caller’s turnId is that request ID. A completed turn’s result is cached under its turnId, so a retry after a lost response reads the result instead of running the work again. The example below keys one customer’s sandbox with ensure, then sends the same turnId on every poll until the turn reaches completed.
import { readFile } from "node:fs/promises";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
// One sandbox per customer. The platform keeps it, resumes it, replaces it.
export async function review(customerId: string, turnId: string, contract: string) {
const instance = await client.instances.ensure({
key: `customer:${customerId}`,
profile: {
version: "contracts-v1",
backend: {
type: "opencode",
profile: {
name: "contract-review",
prompt: {
systemPrompt: "You review contracts. Cite the clause for every finding.",
},
},
},
},
create: { resources: { cpuCores: 1, memoryMB: 2048, diskGB: 10 } },
});
await instance.box.write("contracts/msa.md", contract);
const ask = "Review contracts/msa.md. List the indemnity, liability and termination risks.";
let turn = await instance.turn(ask, { thread: "main", turnId });
// Same turnId: pick the turn back up.
while (turn.state === "running") {
await new Promise((wait) => setTimeout(wait, 3_000));
turn = await instance.turn(ask, { thread: "main", turnId });
}
return turn.state === "completed" ? turn.text : turn.state;
}
console.log(await review("acme", "review-1", await readFile("msa.md", "utf8")));The example proves that a single turn reaches completed against production. It does not prove the payment side: the gateway still decides whether the request was paid and admitted before any turn starts.
Test these cases before inviting buyers:
| Test | Expected behavior |
|---|---|
| No payment proof | 402 with requirements and no execution |
| Invalid or expired payment | Rejection with no Job admission |
| Valid payment, queue available | Settlement record plus 202 and a Job or call ID |
| Valid payment, queue unavailable | Clear failure and documented refund or retry policy |
| Response lost after acceptance | Same request ID returns the original Job state |
| Job fails after payment | Result trace identifies the failure and the buyer receives the stated remedy |
| Result is disputed | Evidence can be reviewed without treating payment as a quality verdict |
What the client does after a timeout
A client needs one rule for a lost response. The first request should carry a caller-owned request ID that the service records before payment or execution changes state. The client can then reconcile the request through the service’s documented job or result lookup path.
| What the client knows | Safe next action |
|---|---|
| No payment challenge was received | Check the request log or retry only if the service says the request was not admitted |
402 was received and no payment was sent |
Fix the request or obtain approval; no job should exist yet |
Payment was signed but no 202 was received |
Query the original request ID or contact the documented support path before paying again |
202 and a call ID were received |
Follow the call or Job state; do not treat queue admission as completion |
| A completion was returned but the artifact is missing | Keep the execution record and open a result-integrity failure rather than replaying payment blindly |
The exact status endpoint and retention period belong to the service contract, not to x402. Document those rules beside the price so a caller can recover from a lost response without guessing.
A buyer needs a trace with the receipt
A trace is the record of one invocation from request through result.
A one-shot run returns the placement, text and cost that the envelope needs.
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
// npx tsx gtm-agent.mts stripe.com
const company = process.argv[2] ?? "tangle.tools";
// No sandbox to manage: the Platform picks where the run executes and says why.
const run = await client.run({
profile: {
name: "gtm-research",
prompt: {
systemPrompt: "Research a company before outreach. Quote a page for each claim.",
},
},
prompt: `Read ${company}. Give three facts a seller should know and one opener.`,
http: { hosts: [company, `www.${company}`] },
model: "glm-5.3",
});
console.log(run.placement?.chosen, run.placement?.reason);
console.log(run.text);
console.log(`$${run.costUsd ?? 0}`);run.costUsd is model spend only; sandbox time is billed separately, so a receipt needs both.
It should connect the payment, job, operator, model or tool route, artifacts, checks, and failure state.
The buyer may not need every token or prompt, but the service should state what it cannot observe.
An illustrative response envelope for a long-running job might look like this:
{
"requestId": "buyer-request-42",
"serviceId": "service-17",
"jobIndex": 0,
"callId": "call-8f2d",
"status": "completed",
"payment": {
"network": "eip155:84532",
"token": "USDC",
"quoteDigest": "sha256:...",
"settlementId": "0x..."
},
"execution": {
"operator": "0xOperator",
"route": "router-model-id",
"startedAt": "2026-06-27T10:00:00Z",
"finishedAt": "2026-06-27T10:00:08Z"
},
"result": {
"artifactUrl": "https://service.example/results/call-8f2d",
"checks": ["schema-valid", "citation-present"]
},
"traceId": "trace-91c0"
}
The envelope is illustrative. Do not publish a field unless the service can populate it and explain its provenance. An operator address says who ran the Service according to the service record. It does not prove that the output was good.
Attestation narrows one trust question
Some services need to protect inputs or prove which software ran. A TEE, or Trusted Execution Environment, is a hardware-backed execution boundary. An attestation is signed evidence about that boundary, often including a code measurement and the policy used to check it.
Attestation can support a claim such as “the expected image ran in the expected confidential environment.” It cannot prove that an AI classification is correct, that the output deserves payment, or that the job followed a business rule unless the result is bound to the attested execution and checked separately. The Tangle TEE attestation guide describes those boundaries.
If a paid service advertises attestation, publish the measurement, the verification service and policy, input and output binding, timestamp, and failure behavior. If that verification process cannot establish those links, return an untrusted or unavailable result rather than a vague “verified” badge.
Result quality needs its own evaluation
An evaluation, or eval, is a repeatable run over a defined set of cases with a scoring rule. For a document service, the cases include an unreadable scan and a request that violates the input policy.
Use deterministic checks for schema validity, required artifact presence, citations, calculations, and policy constraints. Use a model judge for qualities that require interpretation only when the judge version and rubric are recorded. Keep the buyer’s result and the evaluation record linked to the same Job or trace ID.
The Tangle verification guide covers that match. The agent-eval repository documents cases, judges and comparisons.
Payment and evaluation answer separate questions:
| Question | Evidence |
|---|---|
| Did the caller satisfy the price? | Payment requirements, signed payload, verification, and settlement record |
| Did a Service accept the Job? | 202 response, Job or call ID, and queue state |
| Did an operator run the Job? | Execution record, operator identity, and trace |
| Did the claimed environment run? | Attestation or other environment evidence, when offered |
| Is the result acceptable? | Task-specific check, evaluation, replay, or human review |
The first deployment test
Before opening a paid endpoint, run one testnet or otherwise disposable job through the full path. Use a fixed input and collect these records:
- Discovery response and job schema.
- Price response, supported network, token, and expiry.
- Unpaid
402response. - Invalid-payment rejection.
- Valid payment verification and settlement result.
202queue admission with a call or Job ID.- Successful result and task-specific check.
- Deliberate execution failure and its remedy.
- Duplicate request with the same request ID.
- Trace and artifact retrieval after the client disconnects.
Keep payment test funds and credentials separate from production. Publish an agent-facing discovery contract containing the endpoint, JSON schema, price, network, and authorization rules so programmatic buyers do not have to scrape a marketing page. Use the Blueprint deployment guide for the payment-specific implementation path.
The decision for an operator
Publish one paid AI job when a buyer can trace it from discovery to payment, queue admission, execution, and result review. Keep it private while a settled payment can disappear into an unknown queue state, while a retry can create duplicate work, or while the result has no check beyond the model’s prose.
Add more jobs, models, operators, or pricing options after the first job’s failure policies are visible and tested. The first production milestone is a buyer who can tell whether the service owes a result, a refund, a retry, or a review without opening a support ticket to learn what happened.
Is x402 required for a paid AI agent service?
No. x402 fits programmatic pay-per-request access over HTTP, while subscriptions, accounts, invoices, or enterprise contracts may fit longer-lived relationships better.
What does a 402 Payment Required response mean?
It means the server is asking the client to satisfy published payment requirements before it fulfills the protected request. With x402, the client reads those requirements, creates a signed payment payload, and retries the request.
Does a 202 Accepted response mean the AI job succeeded?
No.
For Tangle’s x402 gateway, 202 Accepted means the paid request was accepted and enqueued.
The Service must provide a later completion or failure state.
What should an operator verify before launch?
Verify the discovery contract, price and expiry, authorization, unpaid and invalid-payment paths, health, queue admission, execution, retry behavior, result checks, trace retention, and the remedy for a paid failure.
Does a healthy operator guarantee a good result?
No. Health indicates that the service can answer its health probe or accept work according to its current checks. Result quality requires a separate task-specific evaluation or review.
Why begin with a focused Job?
One job keeps the payment, retry, execution, and evidence states small enough to inspect. It exposes missing failure policies before multiple buyers and operators depend on them.
Next in Tangle Network Protocol: TEE Attestation for AI Services: What the Evidence Proves