Skip to content

πŸ™Œ OpenHands: AI-Driven Development

chore: enforce typed @openhands/typescript-client for agent-server API calls (no ad-hoc fetch) (#16508)

Graham Neubigc4593b8154b8
diff --git a/eslint.config.js b/eslint.config.js
index 0469eabf81..42307db232 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -46,6 +46,54 @@ const compat = new FlatCompat({
resolvePluginsRelativeTo: __dirname,
});
+/**
+ * ESLint rule: forbid raw `fetch` calls that target an agent-server `/api/...`
+ * path, so API access goes through the typed @openhands/typescript-client
+ * clients. Only statically-resolvable agent-server paths are flagged; external
+ * URLs, dynamic identifiers, and non-`/api/` draws (cookie-auth static
+ * fileserver, OAuth device verification) are left alone.
+ */
+function createNoDirectAgentServerFetchRule() {
+ return {
+ meta: {
+ type: "problem",
+ docs: {
+ description:
+ "Use typed @openhands/typescript-client clients instead of global fetch for agent-server API calls.",
+ },
+ messages: {
+ noRawFetch:
+ "Use a typed @openhands/typescript-client client (or AgentServerClient.request) instead of global fetch for agent-server API calls.",
+ },
+ },
+ create(context) {
+ function resolveStaticUrl(node) {
+ if (node.type === "Literal" && typeof node.value === "string") {
+ return node.value;
+ }
+ if (node.type === "TemplateLiteral") {
+ return node.quasis
+ .map((q) => q.value.raw)
+ .join("");
+ }
+ return null;
+ }
+
+ return {
+ CallExpression(node) {
+ const callee = node.callee;
+ if (callee.type !== "Identifier" || callee.name !== "fetch") return;
+ const urlNode = node.arguments[0];
+ if (!urlNode) return;
+ const url = resolveStaticUrl(urlNode);
+ if (url === null || !url.includes("/api/")) return;
+ context.report({ node, messageId: "noRawFetch" });
+ },
+ };
+ },
+ };
+}
+
export default [
// Files / dirs we never want to lint.
{
@@ -112,6 +160,14 @@ export default [
// `// eslint-disable-next-line import/foo` comments keep working.
import: importXPlugin,
prettier: prettierPlugin,
+ // Local rule enforcing that agent-server API calls go through the typed
+ // @openhands/typescript-client clients instead of a raw `fetch`.
+ local: {
+ rules: {
+ "no-direct-agent-server-fetch":
+ createNoDirectAgentServerFetchRule(),
+ },
+ },
},
settings: {
react: { version: "detect" },
@@ -205,6 +261,14 @@ export default [
],
},
],
+ // All agent-server API access must go through the typed
+ // @openhands/typescript-client clients. A raw global `fetch` against an
+ // agent-server `/api/...` path bypasses the typed access layer, so it is
+ // banned here (see also src/api/no-direct-agent-server-calls.test.ts).
+ // Browser-cookie-auth and external (non-agent-server) fetches β€” e.g. the
+ // workspace static fileserver, OAuth device verification, and the npm
+ // registry version check β€” do not target `/api/...` and are unaffected.
+ "local/no-direct-agent-server-fetch": "error",
// Allow `interface Foo extends Bar<"foo"> {}` β€” the codebase uses this
// discriminated-union pattern in `src/types/agent-server/**` and the
diff --git a/src/api/llm-balance-service.test.ts b/src/api/llm-balance-service.test.ts
index 134bc8951e..eb5963d9b5 100644
--- a/src/api/llm-balance-service.test.ts
+++ b/src/api/llm-balance-service.test.ts
@@ -4,7 +4,20 @@ import {
setRegisteredBackends,
} from "#/api/backend-registry/active-store";
import type { Backend } from "#/api/backend-registry/types";
+import {
+ LLM_BALANCE_PATH,
+ LLM_BALANCE_TIMEOUT_MS,
+} from "#/constants/llm-balance";
import LLMBalanceService from "./llm-balance-service";
+import { AgentServerClient } from "@openhands/typescript-client/clients";
+
+const getMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ AgentServerClient: vi.fn(function AgentServerClientMock() {
+ return { get: getMock, close: vi.fn() };
+ }),
+}));
const localBackend: Backend = {
id: "local-test",
@@ -25,16 +38,19 @@ const balancePayload = {
is_free_tier: false,
};
-function mockFetchResponse(status: number, body?: unknown) {
- return vi.fn().mockResolvedValue({
- ok: status >= 200 && status < 300,
- status,
- json: async () => body,
- });
+function httpError(status: number): Error & { status: number } {
+ return Object.assign(new Error(`HTTP ${status}`), { status });
+}
+
+function mockedClient(): AgentServerClient {
+ return vi.mocked(AgentServerClient).mock.results[0]
+ ?.value as AgentServerClient;
}
describe("LLMBalanceService.getBalance", () => {
beforeEach(() => {
+ getMock.mockReset();
+ vi.mocked(AgentServerClient).mockClear();
setRegisteredBackends([localBackend]);
setActiveSelection({ backendId: localBackend.id });
});
@@ -42,13 +58,10 @@ describe("LLMBalanceService.getBalance", () => {
afterEach(() => {
setActiveSelection(null);
setRegisteredBackends([]);
- vi.unstubAllGlobals();
- vi.clearAllMocks();
});
- it("normalizes a successful balance response", async () => {
- const fetchMock = mockFetchResponse(200, balancePayload);
- vi.stubGlobal("fetch", fetchMock);
+ it("normalizes a successful balance response via the typed client", async () => {
+ getMock.mockResolvedValue(balancePayload);
const balance = await LLMBalanceService.getBalance();
@@ -63,22 +76,25 @@ describe("LLMBalanceService.getBalance", () => {
isFreeTier: false,
});
- const [url, init] = fetchMock.mock.calls[0];
- expect(url).toBe("http://localhost:3000/api/llm/balance");
- expect((init.headers as Headers).get("X-Session-API-Key")).toBe(
- "test-session-key",
- );
+ expect(vi.mocked(AgentServerClient)).toHaveBeenCalledWith({
+ host: "http://localhost:3000",
+ apiKey: "test-session-key",
+ timeout: LLM_BALANCE_TIMEOUT_MS,
+ });
+ expect(getMock).toHaveBeenCalledWith(LLM_BALANCE_PATH, {
+ acceptableStatusCodes: new Set([200]),
+ responseType: "json",
+ timeoutSeconds: Math.floor(LLM_BALANCE_TIMEOUT_MS / 1000),
+ });
+ expect(mockedClient().close).toHaveBeenCalled();
});
it("treats null caps as an uncapped key", async () => {
- vi.stubGlobal(
- "fetch",
- mockFetchResponse(200, {
- ...balancePayload,
- limit: null,
- limit_remaining: null,
- }),
- );
+ getMock.mockResolvedValue({
+ ...balancePayload,
+ limit: null,
+ limit_remaining: null,
+ });
const balance = await LLMBalanceService.getBalance();
@@ -88,45 +104,28 @@ describe("LLMBalanceService.getBalance", () => {
});
it("returns null when the endpoint is missing (404)", async () => {
- vi.stubGlobal("fetch", mockFetchResponse(404));
+ getMock.mockRejectedValue(httpError(404));
await expect(LLMBalanceService.getBalance()).resolves.toBeNull();
});
it("returns null for a malformed response body", async () => {
- vi.stubGlobal("fetch", mockFetchResponse(200, { unexpected: true }));
+ getMock.mockResolvedValue({ unexpected: true });
await expect(LLMBalanceService.getBalance()).resolves.toBeNull();
});
it("throws on non-404 HTTP failures", async () => {
- vi.stubGlobal("fetch", mockFetchResponse(500));
+ getMock.mockRejectedValue(httpError(500));
await expect(LLMBalanceService.getBalance()).rejects.toThrow(
"Balance request failed with 500",
);
});
- it("bounds the request with an abort signal", async () => {
- const fetchMock = mockFetchResponse(200, balancePayload);
- vi.stubGlobal("fetch", fetchMock);
-
- await LLMBalanceService.getBalance();
-
- const [, init] = fetchMock.mock.calls[0];
- expect(init.signal).toBeInstanceOf(AbortSignal);
- });
-
it("throws a named error when the request times out", async () => {
- // A server that accepts the connection and never answers: fetch rejects
- // with the signal's TimeoutError rather than resolving.
- vi.stubGlobal(
- "fetch",
- vi
- .fn()
- .mockRejectedValue(
- new DOMException("The operation was aborted.", "TimeoutError"),
- ),
+ getMock.mockRejectedValue(
+ new DOMException("The operation was aborted.", "TimeoutError"),
);
await expect(LLMBalanceService.getBalance()).rejects.toThrow(
diff --git a/src/api/llm-balance-service.ts b/src/api/llm-balance-service.ts
index 5a56b1b58d..de1635705c 100644
--- a/src/api/llm-balance-service.ts
+++ b/src/api/llm-balance-service.ts
@@ -1,3 +1,4 @@
+import { AgentServerClient } from "@openhands/typescript-client/clients";
import { getAgentServerClientOptions } from "./agent-server-client-options";
import {
LLM_BALANCE_PATH,
@@ -67,36 +68,45 @@ class LLMBalanceService {
* absent endpoint would hide the card for the rest of the conversation.
*/
static async getBalance(): Promise<LLMBalance | null> {
- // Raw fetch is deliberate: /api/llm/balance has no typed client in
- // @openhands/typescript-client yet. The file is listed in
- // ALLOWED_AD_HOC_HTTP_FILES (no-direct-agent-server-calls.test.ts) with
- // this justification.
const { host, apiKey } = getAgentServerClientOptions();
- const headers = new Headers({ Accept: "application/json" });
- if (apiKey) {
- headers.set("X-Session-API-Key", apiKey);
- }
-
- let response: Response;
+ const client = new AgentServerClient({
+ host,
+ apiKey,
+ timeout: LLM_BALANCE_TIMEOUT_MS,
+ });
try {
- response = await fetch(`${host}${LLM_BALANCE_PATH}`, {
- headers,
- signal: AbortSignal.timeout(LLM_BALANCE_TIMEOUT_MS),
+ const data = await client.get<unknown>(LLM_BALANCE_PATH, {
+ acceptableStatusCodes: new Set([200]),
+ responseType: "json",
+ timeoutSeconds: Math.floor(LLM_BALANCE_TIMEOUT_MS / 1000),
});
+ return normalizeBalance(data);
} catch (error) {
+ // Older servers without balance support answer 404 β€” hide the UI.
+ if (
+ error instanceof Error &&
+ "status" in error &&
+ (error as { status: number }).status === 404
+ ) {
+ return null;
+ }
if (isAbortLike(error)) {
throw new Error(
`Balance request timed out after ${LLM_BALANCE_TIMEOUT_MS}ms`,
);
}
- throw error;
- }
-
- if (response.status === 404) return null;
- if (!response.ok) {
- throw new Error(`Balance request failed with ${response.status}`);
+ const status =
+ error instanceof Error &&
+ "status" in error &&
+ (error as { status: number }).status;
+ throw new Error(
+ status
+ ? `Balance request failed with ${status}`
+ : `Balance request failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ } finally {
+ client.close();
}
- return normalizeBalance(await response.json());
}
}
diff --git a/src/api/llm-subscription-service.ts b/src/api/llm-subscription-service.ts
index 815e145f52..dea3dfe9b6 100644
--- a/src/api/llm-subscription-service.ts
+++ b/src/api/llm-subscription-service.ts
@@ -1,3 +1,4 @@
+import { AgentServerClient } from "@openhands/typescript-client/clients";
import { getAgentServerClientOptions } from "./agent-server-client-options";
import {
OPENAI_SUBSCRIPTION_DEVICE_POLL_PATH,
@@ -70,25 +71,27 @@ const readBoolean = (
return false;
};
+interface SubscriptionRequestOptions {
+ method?: "GET" | "POST";
+ jsonBody?: unknown;
+}
+
async function requestSubscriptionEndpoint(
path: string,
- init: RequestInit = {},
+ options: SubscriptionRequestOptions = {},
): Promise<unknown> {
const { host, apiKey } = getAgentServerClientOptions();
- const headers = new Headers(init.headers);
- headers.set("Accept", "application/json");
- if (init.body && !headers.has("Content-Type")) {
- headers.set("Content-Type", "application/json");
- }
- if (apiKey) {
- headers.set("X-Session-API-Key", apiKey);
- }
-
- const response = await fetch(`${host}${path}`, { ...init, headers });
- if (!response.ok) {
- throw new Error(`Subscription request failed with ${response.status}`);
+ const client = new AgentServerClient({ host, apiKey });
+ try {
+ return await client.request<unknown>({
+ method: options.method ?? "GET",
+ path,
+ body: options.jsonBody,
+ responseType: "json",
+ });
+ } finally {
+ client.close();
}
- return response.json();
}
function normalizeModels(raw: unknown): string[] {
@@ -181,7 +184,7 @@ class LLMSubscriptionService {
OPENAI_SUBSCRIPTION_DEVICE_POLL_PATH,
{
method: "POST",
- body: JSON.stringify({ device_code: deviceCode }),
+ jsonBody: { device_code: deviceCode },
},
);
return normalizeStatus(response as RawSubscriptionStatus);
diff --git a/src/api/no-direct-agent-server-calls.test.ts b/src/api/no-direct-agent-server-calls.test.ts
index 75761392c4..fcf6b3255d 100644
--- a/src/api/no-direct-agent-server-calls.test.ts
+++ b/src/api/no-direct-agent-server-calls.test.ts
@@ -8,10 +8,6 @@ const ALLOWED_AD_HOC_HTTP_FILES = new Set([
"api/automation-service/automation-service.api.ts",
"api/cloud/proxy.ts",
"api/main-app-auth.ts",
- // GET /api/llm/balance has no typed client in @openhands/typescript-client
- // yet; the service resolves host/key via getAgentServerClientOptions and
- // treats 404 as "endpoint absent" for older servers.
- "api/llm-balance-service.ts",
]);
function collectSourceFiles(dir: string): string[] {