Skip to content

Commit 0d7baff

Browse files
fix(clawrouter): show stable error for malformed usage responses (#119580)
* fix(clawrouter): handle malformed usage responses * fix(clawrouter): use canonical usage record coercion Punchcard-Session: clear-orchard-lantern-bc --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent 29175dd commit 0d7baff

2 files changed

Lines changed: 60 additions & 8 deletions

File tree

‎extensions/clawrouter/usage.test.ts‎

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -222,20 +222,61 @@ describe("ClawRouter usage", () => {
222222
expect(snapshot.summary).toBeUndefined();
223223
});
224224

225-
it("rejects usage JSON containing invalid UTF-8", async () => {
225+
it.each([
226+
["malformed JSON", new TextEncoder().encode('{"budget":')],
227+
["a non-object JSON root", new TextEncoder().encode("null")],
228+
])("reports %s as a malformed usage response", async (_label, body) => {
229+
const snapshot = await fetchClawRouterUsage({
230+
token: "test-token",
231+
timeoutMs: 5000,
232+
fetchGuard: mockFetchGuard(new Response(body)),
233+
});
234+
235+
expect(snapshot).toEqual({
236+
provider: "clawrouter",
237+
displayName: "ClawRouter",
238+
windows: [],
239+
error: "Malformed usage response",
240+
});
241+
});
242+
243+
it("reports invalid UTF-8 as a malformed usage response", async () => {
226244
const prefix = new TextEncoder().encode(
227245
'{"budget":{"configured":true,"windowKey":"default/test-policy/2026-',
228246
);
229247
const suffix = new TextEncoder().encode('","limitMicros":1000000,"spentMicros":500000}}');
230248
const body = new Uint8Array([...prefix, 0xff, ...suffix]);
231249

250+
const snapshot = await fetchClawRouterUsage({
251+
token: "test-token",
252+
timeoutMs: 5000,
253+
fetchGuard: mockFetchGuard(new Response(body)),
254+
});
255+
256+
expect(snapshot).toEqual({
257+
provider: "clawrouter",
258+
displayName: "ClawRouter",
259+
windows: [],
260+
error: "Malformed usage response",
261+
});
262+
});
263+
264+
it("preserves response stream failures as transport errors", async () => {
265+
const response = new Response(
266+
new ReadableStream({
267+
start(controller) {
268+
controller.error(new TypeError("usage stream failed"));
269+
},
270+
}),
271+
);
272+
232273
await expect(
233274
fetchClawRouterUsage({
234275
token: "test-token",
235276
timeoutMs: 5000,
236-
fetchGuard: mockFetchGuard(new Response(body)),
277+
fetchGuard: mockFetchGuard(response),
237278
}),
238-
).rejects.toThrow(TypeError);
279+
).rejects.toThrow("usage stream failed");
239280
});
240281

241282
it("cancels non-OK usage response body before throwing", async () => {

‎extensions/clawrouter/usage.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
fetchWithSsrFGuard,
66
ssrfPolicyFromHttpBaseUrlAllowedHostname,
77
} from "openclaw/plugin-sdk/ssrf-runtime";
8-
import { asFiniteNumberInRange } from "openclaw/plugin-sdk/string-coerce-runtime";
8+
import { asFiniteNumberInRange, asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
99
import { normalizeClawRouterRootUrl } from "./provider-catalog.js";
1010

1111
const CLAWROUTER_USAGE_RESPONSE_MAX_BYTES = 1024 * 1024;
@@ -72,16 +72,19 @@ function buildSummary(payload: ClawRouterUsagePayload): string | undefined {
7272
async function readClawRouterUsagePayload(
7373
response: Response,
7474
timeoutMs: number,
75-
): Promise<ClawRouterUsagePayload> {
75+
): Promise<ClawRouterUsagePayload | undefined> {
7676
const buffer = await readResponseWithLimit(response, CLAWROUTER_USAGE_RESPONSE_MAX_BYTES, {
7777
chunkTimeoutMs: timeoutMs,
7878
onOverflow: ({ maxBytes }) => new Error(`ClawRouter usage response exceeds ${maxBytes} bytes`),
7979
onIdleTimeout: ({ chunkTimeoutMs }) =>
8080
new Error(`ClawRouter usage response stalled: no data received for ${chunkTimeoutMs}ms`),
8181
});
82-
return JSON.parse(
83-
new TextDecoder("utf-8", { fatal: true }).decode(buffer),
84-
) as ClawRouterUsagePayload;
82+
try {
83+
const payload: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(buffer));
84+
return asOptionalRecord(payload) as ClawRouterUsagePayload | undefined;
85+
} catch {
86+
return undefined;
87+
}
8588
}
8689

8790
export async function fetchClawRouterUsage(params: {
@@ -116,6 +119,14 @@ export async function fetchClawRouterUsage(params: {
116119
throw new Error(`ClawRouter usage request failed (HTTP ${response.status})`);
117120
}
118121
const payload = await readClawRouterUsagePayload(response, params.timeoutMs);
122+
if (!payload) {
123+
return {
124+
provider: "clawrouter",
125+
displayName: "ClawRouter",
126+
windows: [],
127+
error: "Malformed usage response",
128+
};
129+
}
119130
const budget = payload.budget;
120131
const limitMicros = asFiniteNumberInRange(budget?.limitMicros, { min: 0 });
121132
const spentMicros = asFiniteNumberInRange(budget?.spentMicros, { min: 0 });

0 commit comments

Comments
 (0)