Skip to content
Open
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
108 changes: 86 additions & 22 deletions packages/sdk/src/agentClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHash, randomUUID } from "crypto";
import { AgentResponse, ChainId, CrossChainSwapRequest } from "./types";
import { AgentResponse, ChainId, CrossChainSwapRequest, CategorizedError } from "./types";
import { SdkError, ErrorCategory, transportError } from "./errors";

/** Input required to generate a stable idempotency key */
export interface IdempotencyKeyInput {
Expand Down Expand Up @@ -60,7 +61,7 @@ export interface ExecuteBtcToStellarSwapOptions {
}

/** Error thrown when an agent request fails after all retries */
export class AgentRequestError extends Error {
export class AgentRequestError extends SdkError {
readonly idempotencyKey: string;
readonly attempts: number;
readonly statusCode?: number;
Expand All @@ -69,9 +70,19 @@ export class AgentRequestError extends Error {
message: string,
idempotencyKey: string,
attempts: number,
statusCode?: number
statusCode?: number,
) {
super(message);
const category = statusCode !== undefined
? categorizeHttpStatus(statusCode)
: ErrorCategory.TRANSPORT;
const code = statusCode !== undefined
? `HTTP_${statusCode}`
: "AGENT_REQUEST_FAILED";
const recoverable = statusCode !== undefined
? RETRIABLE_STATUS_CODES.has(statusCode)
: false;

super({ category, code, message, recoverable });
this.name = "AgentRequestError";
this.idempotencyKey = idempotencyKey;
this.attempts = attempts;
Expand Down Expand Up @@ -102,6 +113,14 @@ type FetchLike = (

const RETRIABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);

function categorizeHttpStatus(status: number): ErrorCategory {
if (status === 429) return ErrorCategory.POLICY;
if (status === 422 || status === 400) return ErrorCategory.VALIDATION;
if (status === 401 || status === 403) return ErrorCategory.POLICY;
if (status >= 500) return ErrorCategory.EXECUTION;
return ErrorCategory.TRANSPORT;
}

function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
Expand Down Expand Up @@ -194,6 +213,32 @@ function createTimedSignal(
};
}

/**
* Parse a categorized error from a JSON response body.
*/
function parseCategorizedError(body: string, status: number): CategorizedError {
try {
const parsed = JSON.parse(body);
if (parsed.error && parsed.error.category) {
return {
category: parsed.error.category,
code: parsed.error.code ?? `HTTP_${status}`,
message: parsed.error.message ?? body,
recoverable: parsed.error.recoverable ?? false,
details: parsed.error.details,
};
}
} catch {
// not JSON, fall through
}
return {
category: categorizeHttpStatus(status),
code: `HTTP_${status}`,
message: body,
recoverable: RETRIABLE_STATUS_CODES.has(status),
};
}

/**
* Client for interacting with the Chen Pilot AI Agent backend.
* Provides resilient querying with retries and timeout controls.
Expand Down Expand Up @@ -244,7 +289,12 @@ export class AgentClient {
const retryDelayMs = request.retryDelayMs ?? this.defaultRetryDelayMs;

let attempts = 0;
let lastErrorMessage = "Request failed";
let lastCategorizedError: CategorizedError = {
category: "TRANSPORT",
code: "UNKNOWN",
message: "Request failed",
recoverable: false,
};
let lastStatusCode: number | undefined;

while (attempts < maxRetries) {
Expand All @@ -268,21 +318,20 @@ export class AgentClient {
if (!response.ok) {
lastStatusCode = response.status;
const body = await response.text().catch(() => "");
const message = body || `HTTP ${response.status}`;
lastCategorizedError = parseCategorizedError(body, response.status);

if (
!RETRIABLE_STATUS_CODES.has(response.status) ||
attempts >= maxRetries
) {
throw new AgentRequestError(
`Agent query failed: ${message}`,
`Agent query failed: ${lastCategorizedError.message}`,
idempotencyKey,
attempts,
response.status
response.status,
);
}

lastErrorMessage = `Agent query failed: ${message}`;
await sleep(retryDelayMs * attempts);
continue;
}
Expand All @@ -294,6 +343,10 @@ export class AgentClient {
result: parsed.result,
};
} catch (error) {
if (error instanceof AgentRequestError) {
throw error;
}

const isAbort =
error instanceof Error &&
(error.name === "AbortError" || error.message.includes("aborted"));
Expand All @@ -302,19 +355,23 @@ export class AgentClient {
(error instanceof Error &&
error.message.toLowerCase().includes("network"));

if (error instanceof AgentRequestError) {
throw error;
}

lastErrorMessage =
error instanceof Error ? error.message : String(error);
lastCategorizedError = {
category: isAbort
? "TRANSPORT"
: isNetwork
? "TRANSPORT"
: "UNKNOWN",
code: isAbort ? "REQUEST_ABORTED" : isNetwork ? "NETWORK_ERROR" : "UNKNOWN",
message: error instanceof Error ? error.message : String(error),
recoverable: isNetwork || isAbort,
};

if (!(isAbort || isNetwork) || attempts >= maxRetries) {
throw new AgentRequestError(
`Agent query failed: ${lastErrorMessage}`,
`Agent query failed: ${lastCategorizedError.message}`,
idempotencyKey,
attempts,
lastStatusCode
lastStatusCode,
);
}

Expand All @@ -325,10 +382,10 @@ export class AgentClient {
}

throw new AgentRequestError(
`Agent query failed: ${lastErrorMessage}`,
`Agent query failed: ${lastCategorizedError.message}`,
idempotencyKey,
attempts,
lastStatusCode
lastStatusCode,
);
}

Expand All @@ -347,9 +404,16 @@ export class AgentClient {
swapRequest.fromChain !== ChainId.BITCOIN ||
swapRequest.toChain !== ChainId.STELLAR
) {
throw new Error(
"executeBtcToStellarSwap only supports fromChain=bitcoin and toChain=stellar"
);
throw new SdkError({
category: ErrorCategory.VALIDATION,
code: "INVALID_SWAP_DIRECTION",
message:
"executeBtcToStellarSwap only supports fromChain=bitcoin and toChain=stellar",
details: {
fromChain: swapRequest.fromChain,
toChain: swapRequest.toChain,
},
});
}

const idempotencyKey =
Expand Down
Loading
Loading