Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@ainative/sdk",
"type": "module",
"version": "1.0.0",
"version": "3.2.0",
"description": "Official TypeScript/JavaScript SDK for AINative Studio APIs",
"main": "dist/index.js",
"module": "dist/index.esm.js",
Expand Down
29 changes: 26 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { EventEmitter } from 'eventemitter3';
import { ClientConfig, AuthConfig, RequestOptions, ApiResponse, ApiError } from './types';
import { ZeroDBClient } from './zerodb';
import { AgentSwarmClient } from './agent-swarm';
import { X402Client } from './x402';
import { AuthManager } from './auth';
import {
AINativeError,
Expand All @@ -26,6 +27,7 @@ export class AINativeClient extends EventEmitter {
private authManager: AuthManager;
private _zerodb?: ZeroDBClient;
private _agentSwarm?: AgentSwarmClient;
private _x402?: X402Client;

constructor(config: ClientConfig = {}) {
super();
Expand Down Expand Up @@ -91,6 +93,16 @@ export class AINativeClient extends EventEmitter {
return this._agentSwarm;
}

/**
* Get x402 payment-protocol client (plans, subscribe, subscription status)
*/
get x402(): X402Client {
if (!this._x402) {
this._x402 = new X402Client(this);
}
return this._x402;
}

/**
* Make an authenticated request
*/
Expand Down Expand Up @@ -256,11 +268,22 @@ export class AINativeClient extends EventEmitter {
if (error.response) {
const status = error.response.status;
const data = error.response.data;
const message = data?.detail || data?.message || error.message;
// `detail` is normally a string (the backend's global exception
// handler flattens a structured HTTPException(detail={...}) down to
// a top-level `detail: string` plus sibling keys like `requirements`
// — see app/main.py::http_exception_handler). Guard with a typeof
// check anyway in case some response is a raw dict error body.
const detailMessage = typeof data?.detail === 'string' ? data.detail : undefined;
const message = detailMessage || data?.message || error.message;
// Carry the raw response body + headers through on every branch so a
// typed wrapper (e.g. X402Client) can recover structured fields
// (like a 402's `requirements`, or its WWW-Authenticate header)
// without re-making the request.
const details = { ...data, headers: error.response.headers };

switch (status) {
case 400:
return new ValidationError(message);
return new ValidationError(message, details);
case 401:
return new AuthenticationError(message);
case 403:
Expand All @@ -276,7 +299,7 @@ export class AINativeClient extends EventEmitter {
case 503:
return new ServerError(message, status);
default:
return new AINativeError(message, status.toString(), status);
return new AINativeError(message, status.toString(), status, details);
}
} else if (error.request) {
return new NetworkError('No response received from server');
Expand Down
22 changes: 22 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,26 @@ export class ServerError extends AINativeError {
super(message, 'SERVER_ERROR', status);
this.name = 'ServerError';
}
}

/**
* A 402 Payment Required response from an x402-protected endpoint (e.g.
* `POST /cloud/x402/subscriptions/subscribe`). Carries the structured
* payment requirements (amount, asset, network, pay_to, scheme) parsed
* from the response, so a caller can hand them straight to a wallet/payer
* instead of re-parsing the raw body or header themselves.
*/
export class X402PaymentRequiredError extends AINativeError {
/** Payment requirements parsed from the response (header and/or JSON body). */
public requirements?: Partial<import('./types/x402').X402PaymentRequirements>;

constructor(
message: string = 'Payment required',
requirements?: Partial<import('./types/x402').X402PaymentRequirements>,
details?: any
) {
super(message, 'payment_required', 402, details);
this.name = 'X402PaymentRequiredError';
this.requirements = requirements;
}
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
export { AINativeClient } from './client';
export { ZeroDBClient } from './zerodb';
export { AgentSwarmClient } from './agent-swarm';
export { X402Client, parseX402PaymentHeader, parseX402PaymentHeaderOrThrow } from './x402';

// Export types
export * from './types';
export * from './types/zerodb';
export * from './types/agent-swarm';
export * from './types/x402';

// Export errors
export * from './errors';
Expand Down
98 changes: 98 additions & 0 deletions src/types/x402.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* Type definitions for x402 payment-protocol support.
*
* x402 is the "pay via HTTP 402" convention AINative uses for agent-paid
* subscriptions (core#9247 MPP). The real wire shape comes from
* `app/api/v1/endpoints/x402_subscriptions.py::subscribe_via_x402` in the
* backend: a 402 response carries BOTH a JSON body (`requirements`) and a
* `WWW-Authenticate: Payment ...` header encoding the same fields, so an
* agent can discover payment terms from the header alone.
*/

/**
* The x402 payment requirements, as emitted in both the 402 JSON body
* (`requirements`) and the `WWW-Authenticate: Payment` header.
*
* Field names mirror the backend dict built in `X402SubscriptionService`
* (`amount`, `asset`, `network`, `pay_to`) plus the `scheme` the endpoint
* defaults to `"exact"` when building the header.
*/
export interface X402PaymentRequirements {
/** Payment scheme, e.g. "exact". Defaults to "exact" when absent. */
scheme: string;

/** Settlement network, e.g. "base" or "base-sepolia". */
network: string;

/** Asset the agent must pay with, e.g. "USDC". */
asset: string;

/**
* Amount required, as a string (the header always carries it quoted;
* the JSON body may carry it as a number — callers that need a number
* should parse this themselves).
*/
amount: string;

/** Wallet address the agent must pay to. */
pay_to: string;
}

/** Fields of {@link X402PaymentRequirements} that may legitimately be absent
* from a given `WWW-Authenticate: Payment` header. */
export type X402PaymentRequirementsField = keyof X402PaymentRequirements;

/** Plan identifiers purchasable via x402 (mirrors `SubscribeRequest.plan_id`). */
export type X402PlanId = 'hobbyist' | 'pro' | 'business' | 'enterprise' | 'cody_vcto';

/** Billing mode for an x402 subscription purchase. */
export type X402BillingMode = 'prepaid' | 'recurring';

/** The x402 payment proof an agent submits after paying on-chain/via Circle. */
export interface X402PaymentProof {
tx_hash?: string;
amount?: number;
asset?: string;
network?: string;
[key: string]: unknown;
}

/** Request body for `POST /cloud/x402/subscriptions/subscribe`. */
export interface X402SubscribeRequest {
plan_id: X402PlanId | string;
billing_mode?: X402BillingMode;
wallet_address?: string;
user_id?: string;
/** Omit to get the 402 challenge back; include to activate the subscription. */
payment_proof?: X402PaymentProof;
}

/** A plan purchasable via x402, as returned by `GET /cloud/x402/subscriptions/plans`. */
export interface X402Plan {
id: string;
price_usd?: number;
amount?: number;
asset?: string;
network?: string;
pay_to?: string | null;
[key: string]: unknown;
}

/** Successful (activated) result of `POST /cloud/x402/subscriptions/subscribe`. */
export interface X402Subscription {
status?: string;
plan_id?: string;
wallet_address?: string | null;
user_id?: string | null;
network?: string;
x402_last_tx?: string;
[key: string]: unknown;
}

/** The JSON body of a 402 response from the x402 subscribe endpoint. */
export interface X402ChallengeBody {
detail: string;
error_code: 'payment_required';
next_action: 'submit_x402_payment';
requirements: Partial<X402PaymentRequirements> & Record<string, unknown>;
}
105 changes: 105 additions & 0 deletions src/x402/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* x402 payment-protocol client for TypeScript/JavaScript.
*
* Thin typed wrapper around the backend's x402 subscription endpoints
* (`app/api/v1/endpoints/x402_subscriptions.py`, mounted under
* `/cloud/x402/subscriptions`), so an SDK consumer gets a typed
* {@link X402PaymentRequiredError} (with parsed `requirements`) on the
* standard "pay via HTTP 402" challenge, rather than a raw fetch/axios
* error they have to pick apart themselves.
*/

import type { AINativeClient } from '../client';
import type { ApiResponse } from '../types';
import type {
X402Plan,
X402SubscribeRequest,
X402Subscription,
X402PaymentRequirements
} from '../types/x402';
import { X402PaymentRequiredError } from '../errors';
import { parseX402PaymentHeader } from './parseHeader';

export { parseX402PaymentHeader, parseX402PaymentHeaderOrThrow } from './parseHeader';

export class X402Client {
constructor(private client: AINativeClient) {}

/**
* List every plan purchasable via x402, with its payment target
* (amount, pay_to wallet, network). No auth required — agents shop
* before paying.
*/
async listPlans(): Promise<ApiResponse<{ plans: X402Plan[] }>> {
return this.client.get<{ plans: X402Plan[] }>('/cloud/x402/subscriptions/plans');
}

/**
* Buy a subscription via x402.
*
* - Called **without** `payment_proof`: the backend returns an HTTP 402
* challenge. This method converts that into a thrown
* {@link X402PaymentRequiredError} whose `.requirements` is populated
* from the response — preferring the `WWW-Authenticate: Payment`
* header (the MPP discovery convention, core#9247) and falling back
* to the JSON body's `requirements` field if the header is somehow
* absent — so callers get a single typed shape regardless of which
* carried the data.
* - Called **with** `payment_proof`: resolves normally with the
* activated (or already-active) subscription.
*
* @throws {X402PaymentRequiredError} on the 402 challenge.
* @throws {AINativeError} (or a subclass) on any other failure.
*/
async subscribe(body: X402SubscribeRequest): Promise<ApiResponse<X402Subscription>> {
try {
return await this.client.post<X402Subscription>(
'/cloud/x402/subscriptions/subscribe',
body
);
} catch (error: any) {
if (error?.status === 402) {
throw this.toPaymentRequiredError(error);
}
throw error;
}
}

/** The agent's current x402-activated subscription (by wallet or user_id). */
async getSubscription(params: {
walletAddress?: string;
userId?: string;
}): Promise<ApiResponse<{ subscription: X402Subscription | null }>> {
const query = new URLSearchParams();
if (params.walletAddress) query.append('wallet_address', params.walletAddress);
if (params.userId) query.append('user_id', params.userId);

return this.client.get<{ subscription: X402Subscription | null }>(
`/cloud/x402/subscriptions/subscription?${query}`
);
}

/**
* Convert a caught 402 error (as produced by `AINativeClient`'s error
* handling) into a typed {@link X402PaymentRequiredError}.
*/
private toPaymentRequiredError(error: any): X402PaymentRequiredError {
const headerValue: string | undefined =
error?.details?.headers?.['www-authenticate'] ??
error?.details?.headers?.['WWW-Authenticate'];

const fromHeader = parseX402PaymentHeader(headerValue);
const fromBody: Partial<X402PaymentRequirements> | undefined =
error?.details?.requirements;

const requirements: Partial<X402PaymentRequirements> | undefined =
fromHeader ?? fromBody ?? undefined;

const message: string =
error?.details?.detail ||
error?.message ||
'Payment required — pay the required amount to pay_to, then re-call with payment_proof.';

return new X402PaymentRequiredError(message, requirements, error?.details);
}
}
Loading
Loading