Skip to content

Instantly share code, notes, and snippets.

@Gusser93
Last active November 7, 2026 02:32
Show Gist options
  • Select an option

  • Save Gusser93/412375b07102a50562bddc6efaae8d25 to your computer and use it in GitHub Desktop.

Select an option

Save Gusser93/412375b07102a50562bddc6efaae8d25 to your computer and use it in GitHub Desktop.
Retry plugin for openCode
import { Plugin } from "@opencode/plugin";
import fs from "fs";
// FIXME: Implement a better way to do this
// can be used to get the exact message provided in the error
const LOG_FILE = "/sandbox/log.log";
function log(msg: string) {
try {
fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] ${msg}\n`);
} catch {}
}
function msUntilReset(message: string, now: number = Date.now()): number {
// TODO: Change this to match your error message
const match = message.match(
/Limit resets at:\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) UTC/,
);
if (!match) {
log(`No reset timestamp found: ${message}`);
throw new Error("No reset timestamp found in message");
}
const resetAt = Date.parse(match[1].replace(" ", "T") + "Z");
if (Number.isNaN(resetAt)) {
throw new Error(`Could not parse timestamp: ${match[1]}`);
}
return Math.max(0, resetAt - now);
}
export default Plugin.define({
id: "Retry",
async setup(ctx) {
const rate_limit_error_codes = ctx.options.error_codes || [429, 400];
await ctx.session.hook("retry", (event) => {
if (rate_limit_error_codes.includes(event.error.status)) {
//log(`Rate limited (${event.error.status}) — retrying`);
let delay = 5 * 60 * 1_000; // default 5 minutes
try {
// Couldn't find a way to get response headers in the retry hook
// You could probably use the http.response hook
// but I did'n to want check every message
delay = msUntilReset(event.error.message);
} catch {
//log("Falling back to 5-minute delay");
}
event.decision = { retry: true, delay };
return;
}
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment