Skip to content

Commit f6f6bfc

Browse files
giodl73-repoGio Della-Libera
andauthored
fix(router): fall back when public reads are throttled (#1054)
* fix(router): fall back when public reads are throttled Retry public OpenClaw reads once with the target GitHub App token when the public-read installation is rate limited. Explicit credentials, mutations, request bodies, and non-GitHub hosts keep their existing credential boundaries. Co-authored-by: Copilot <[email protected]> Copilot-Session: 3cdcdb00-ade8-4e61-85a7-8151b35f216a * fix(router): bound App-token fallback per run Allow at most one public-read recovery for each target App credential in a process. Repeated public throttles fail closed while later privileged mutations retain their configured App-token path. Co-authored-by: Copilot <[email protected]> Copilot-Session: 3cdcdb00-ade8-4e61-85a7-8151b35f216a --------- Co-authored-by: Gio Della-Libera <[email protected]> Copilot-Session: 3cdcdb00-ade8-4e61-85a7-8151b35f216a
1 parent 2eb1787 commit f6f6bfc

2 files changed

Lines changed: 134 additions & 4 deletions

File tree

‎src/repair/github-cli.ts‎

Lines changed: 82 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ export type GhRetryOptions = GhRunOptions & {
2121
attempts?: number;
2222
};
2323

24+
type PublicReadFallback = {
25+
appToken: string;
26+
options: GhRunOptions;
27+
};
28+
29+
const claimedPublicReadFallbackTokens = new Set<string>();
30+
2431
export function ghJson<T = JsonValue>(ghArgs: string[], options: GhRunOptions = {}): T {
2532
return JSON.parse(ghText(ghArgs, options) || "null") as T;
2633
}
@@ -169,13 +176,32 @@ export function ghText(ghArgs: string[], options: GhRunOptions = {}): string {
169176
export function ghTextWithRetry(ghArgs: string[], options: GhRetryOptions | number = {}): string {
170177
const resolved = resolveRetryOptions(options);
171178
const attempts = Math.max(1, resolved.attempts ?? 6);
179+
let activeOptions: GhRunOptions = resolved;
180+
const publicReadFallback = publicReadFallbackOptions(ghArgs, resolved);
172181
let lastError: unknown;
173182
for (let attempt = 1; attempt <= attempts; attempt += 1) {
174183
try {
175-
return ghText(ghArgs, resolved);
184+
return ghText(ghArgs, activeOptions);
176185
} catch (error) {
177186
lastError = error;
178187
const retryKind = ghRetryKind(error);
188+
const fallback =
189+
retryKind === "throttle" ? claimPublicReadFallback(publicReadFallback) : null;
190+
if (retryKind === "throttle" && fallback) {
191+
activeOptions = fallback;
192+
try {
193+
return ghText(ghArgs, fallback);
194+
} catch (fallbackError) {
195+
lastError = fallbackError;
196+
const fallbackRetryKind = ghRetryKind(fallbackError);
197+
if (fallbackRetryKind === "throttle") {
198+
throw new GitHubRateLimitError(fallbackError);
199+
}
200+
if (attempt >= attempts || fallbackRetryKind === "none") throw fallbackError;
201+
sleepMs(ghRetryWaitMs(fallbackRetryKind, attempt - 1));
202+
continue;
203+
}
204+
}
179205
if (retryKind === "throttle") throw new GitHubRateLimitError(error);
180206
if (attempt >= attempts || retryKind === "none") throw error;
181207
sleepMs(ghRetryWaitMs(retryKind, attempt - 1));
@@ -190,13 +216,32 @@ export async function ghTextWithRetryAsync(
190216
): Promise<string> {
191217
const resolved = resolveRetryOptions(options);
192218
const attempts = Math.max(1, resolved.attempts ?? 6);
219+
let activeOptions: GhRunOptions = resolved;
220+
const publicReadFallback = publicReadFallbackOptions(ghArgs, resolved);
193221
let lastError: unknown;
194222
for (let attempt = 1; attempt <= attempts; attempt += 1) {
195223
try {
196-
return await ghTextAsync(ghArgs, resolved);
224+
return await ghTextAsync(ghArgs, activeOptions);
197225
} catch (error) {
198226
lastError = error;
199227
const retryKind = ghRetryKind(error);
228+
const fallback =
229+
retryKind === "throttle" ? claimPublicReadFallback(publicReadFallback) : null;
230+
if (retryKind === "throttle" && fallback) {
231+
activeOptions = fallback;
232+
try {
233+
return await ghTextAsync(ghArgs, fallback);
234+
} catch (fallbackError) {
235+
lastError = fallbackError;
236+
const fallbackRetryKind = ghRetryKind(fallbackError);
237+
if (fallbackRetryKind === "throttle") {
238+
throw new GitHubRateLimitError(fallbackError);
239+
}
240+
if (attempt >= attempts || fallbackRetryKind === "none") throw fallbackError;
241+
await sleepAsync(ghRetryWaitMs(fallbackRetryKind, attempt - 1));
242+
continue;
243+
}
244+
}
200245
if (retryKind === "throttle") throw new GitHubRateLimitError(error);
201246
if (attempt >= attempts || retryKind === "none") throw error;
202247
await sleepAsync(ghRetryWaitMs(retryKind, attempt - 1));
@@ -256,6 +301,17 @@ export function ghEnv(overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
256301
function ghCommandEnv(ghArgs: readonly string[], options: GhRunOptions): NodeJS.ProcessEnv {
257302
const overrides = options.env ?? {};
258303
const env = ghEnv(overrides);
304+
const publicToken = publicReadToken(ghArgs, options, env);
305+
if (!publicToken) return env;
306+
return ghEnv({ ...overrides, GH_TOKEN: publicToken });
307+
}
308+
309+
function publicReadToken(
310+
ghArgs: readonly string[],
311+
options: GhRunOptions,
312+
env = ghEnv(options.env ?? {}),
313+
): string | null {
314+
const overrides = options.env ?? {};
259315
const publicToken = process.env.CLAWSWEEPER_PUBLIC_GH_TOKEN?.trim();
260316
if (
261317
!publicToken ||
@@ -265,9 +321,31 @@ function ghCommandEnv(ghArgs: readonly string[], options: GhRunOptions): NodeJS.
265321
(env.GH_HOST && env.GH_HOST.toLowerCase() !== "github.com") ||
266322
!isPublicOpenClawReadOnlyRequest(ghArgs)
267323
) {
268-
return env;
324+
return null;
269325
}
270-
return ghEnv({ ...overrides, GH_TOKEN: publicToken });
326+
return publicToken;
327+
}
328+
329+
function publicReadFallbackOptions(
330+
ghArgs: readonly string[],
331+
options: GhRunOptions,
332+
): PublicReadFallback | null {
333+
const overrides = options.env ?? {};
334+
const publicToken = publicReadToken(ghArgs, options);
335+
const appToken = process.env.GH_TOKEN?.trim();
336+
if (!publicToken || !appToken || publicToken === appToken) {
337+
return null;
338+
}
339+
return {
340+
appToken,
341+
options: { ...options, env: { ...overrides, GH_TOKEN: appToken } },
342+
};
343+
}
344+
345+
function claimPublicReadFallback(fallback: PublicReadFallback | null): GhRunOptions | null {
346+
if (!fallback || claimedPublicReadFallbackTokens.has(fallback.appToken)) return null;
347+
claimedPublicReadFallbackTokens.add(fallback.appToken);
348+
return fallback.options;
271349
}
272350

273351
export function ghErrorText(error: unknown): string {

‎test/repair/github-cli.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import test from "node:test";
33

44
import {
55
ghJson,
6+
ghJsonWithRetry,
67
ghJsonWithRetryAsync,
78
ghSpawn,
89
githubLimitedPagePath,
@@ -131,3 +132,54 @@ test("public target reads preserve GitHub App mutations and every explicit crede
131132
}
132133
}
133134
});
135+
136+
test("public read throttles fall back once to the target App token", async () => {
137+
const fixtureEnv = {
138+
GH_BIN: process.execPath,
139+
GH_BIN_ARGS: JSON.stringify([
140+
"--eval",
141+
[
142+
'if (process.env.GH_TOKEN?.startsWith("public-read-token")) {',
143+
' process.stderr.write("gh: API rate limit exceeded for installation (HTTP 403)\\n");',
144+
" process.exit(1);",
145+
"}",
146+
"process.stdout.write(JSON.stringify({ token: process.env.GH_TOKEN }));",
147+
].join("\n"),
148+
"--",
149+
]),
150+
GH_TOKEN: "app-mutation-token",
151+
CLAWSWEEPER_PUBLIC_GH_TOKEN: "public-read-token",
152+
};
153+
const previous = Object.fromEntries(
154+
Object.keys(fixtureEnv).map((key) => [key, process.env[key]]),
155+
);
156+
Object.assign(process.env, fixtureEnv);
157+
158+
try {
159+
const args = ["api", "repos/openclaw/openclaw/issues/123"];
160+
assert.equal(ghJsonWithRetry<{ token: string }>(args).token, "app-mutation-token");
161+
assert.throws(() => ghJsonWithRetry(args), { name: "GitHubRateLimitError" });
162+
163+
process.env.GH_TOKEN = "app-mutation-token-async";
164+
process.env.CLAWSWEEPER_PUBLIC_GH_TOKEN = "public-read-token-async";
165+
assert.equal(
166+
(await ghJsonWithRetryAsync<{ token: string }>(args)).token,
167+
"app-mutation-token-async",
168+
);
169+
170+
process.env.GH_TOKEN = "app-mutation-token";
171+
process.env.CLAWSWEEPER_PUBLIC_GH_TOKEN = "public-read-token";
172+
assert.equal(
173+
ghJsonWithRetry<{ token: string }>(
174+
["api", "--method", "POST", "repos/openclaw/openclaw/issues/123/labels"],
175+
{ input: "{}" },
176+
).token,
177+
"app-mutation-token",
178+
);
179+
} finally {
180+
for (const [key, value] of Object.entries(previous)) {
181+
if (value === undefined) delete process.env[key];
182+
else process.env[key] = value;
183+
}
184+
}
185+
});

0 commit comments

Comments
 (0)