Skip to content
Open
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
34 changes: 33 additions & 1 deletion src/acpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ import { USDC_TOKEN_ADDRESS } from "./constants";
import axios, { AxiosError, AxiosInstance } from "axios";
import AcpAgent from "./acpAgent";

declare module "axios" {
interface InternalAxiosRequestConfig {
_retryCount?: number;
}
}

const { version } = require("../package.json");

enum SocketEvents {
Expand Down Expand Up @@ -110,13 +116,34 @@ class AcpClient {
return config;
});

this.acpClient.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;

if (
error.response?.status === 401 &&
(originalRequest._retryCount ?? 0) < 2
) {
originalRequest._retryCount = (originalRequest._retryCount ?? 0) + 1;

const newToken = await this.forceRefreshToken();
originalRequest.headers["authorization"] = `Bearer ${newToken}`;

return this.acpClient.request(originalRequest);
}

return Promise.reject(error);
}
);

this.onNewTask = options.onNewTask;
this.onEvaluate = options.onEvaluate || this.defaultOnEvaluate;

this.init(options.skipSocketConnection);
}

private async getAccessToken() {
public async getAccessToken() {
if (this.accessTokenInflight) {
return await this.accessTokenInflight;
}
Expand Down Expand Up @@ -162,6 +189,11 @@ class AcpClient {
return verified.accessToken;
}

private async forceRefreshToken() {
this.accessToken = null;
return await this.getAccessToken();
}

private async getAuthChallenge() {
try {
const response = await this.noAuthAcpClient.get<{
Expand Down
Loading