mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
On the reference box a tool schema the provider refused (HTTP 400, which opencode marks isRetryable false) came back 91 times in 28 minutes over 12 sessions, nearly always within a second of its relaunch, one session up to the cap of 25 (2026-10-13). Only such refusals count: a retryable error keeps the 25, since there one session got the same "engine restarted" answer 9 times in a row before the engine served it again. Numbers in the message do not make a new refusal, and the idle that ends a refused turn is not progress. AC_SAME_REFUSAL_MAX sets the count. Tests: the refusal one fails on v1.28.1, the retryable one on a rule that counted every error, and five mutants fail them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
209 lines
9.6 KiB
JavaScript
209 lines
9.6 KiB
JavaScript
// auto-continue: automatically resumes an opencode session interrupted by a
|
|
// TECHNICAL error (tool-call delta without id, timeout, network reset...), OR
|
|
// left stuck right after a compaction (context compacted but the turn does not
|
|
// restart on its own), so a one-off incident no longer freezes a long run.
|
|
// Battle-tested on the reference box (errors 2026-08-24, compaction 2026-08-25),
|
|
// zero dependencies.
|
|
// Log: ~/.config/qwen38/auto-continue.log (override with AC_LOG).
|
|
// Install: cp auto-continue.js ~/.config/opencode/plugins/
|
|
// Plugins load at opencode startup only: a new session picks it up, a running
|
|
// one never does.
|
|
import { appendFile } from "node:fs/promises";
|
|
|
|
const num = (v, d) => {
|
|
const n = Number(v);
|
|
return Number.isFinite(n) ? n : d;
|
|
};
|
|
|
|
const LOG = process.env.AC_LOG || process.env.HOME + "/.config/qwen38/auto-continue.log";
|
|
const THROTTLE_MS = num(process.env.AC_THROTTLE_MS, 5000); // minimum between two relaunches of one session
|
|
const IDLE_DELAY_MS = num(process.env.AC_IDLE_DELAY_MS, 1500); // breather after idle before relaunching
|
|
const MAX_CONSECUTIVE = num(process.env.AC_MAX_CONSECUTIVE, 25); // relaunches in a row without any progress
|
|
// A request refused as sent (an API error opencode itself will not retry: isRetryable false, a
|
|
// 400) that comes back the same this many times in a row will not go away: on the reference box a
|
|
// tool schema the provider refused came back 91 times in 28 minutes over 12 sessions, nearly always
|
|
// within a second of its relaunch, one session up to the cap of 25 (2026-10-13). A retryable error
|
|
// (an engine restarting or unreachable, a 429, a provider timeout) keeps the whole budget: there one
|
|
// session got the same "engine restarted" answer 9 times in a row before the engine served it again.
|
|
const SAME_REFUSAL_MAX = num(process.env.AC_SAME_REFUSAL_MAX, 3);
|
|
// never relaunch on these: a deliberate user action, or a problem that will
|
|
// not fix itself
|
|
const EXCLUDE = ["abort", "interrupt", "permission", "unauthorized", "auth", "payment", "quota",
|
|
// A prompt past what the lane serves, or an image the engine cannot decode: a relaunch
|
|
// sends the same history plus its own reminder, so it can only fail again, longer
|
|
// (the reference box's log, 2026-09-09: 210,159 then 210,210 then 210,261 tokens against
|
|
// a 200,000 ceiling). opencode compacts on an overflow by itself, and a compaction that
|
|
// does not resume is the compaction path's to relaunch. The last three are the proxy's
|
|
// wording before its refusal read as an overflow to opencode.
|
|
"contextoverflow", "context_too_long", "prompt is too long", "serves at most",
|
|
"tokens by size", "imagedecodeerror", "could not be decoded"];
|
|
|
|
const RESUME_AFTER_ERROR = "<system-reminder>The previous turn was interrupted by a transient technical error, not by the user. Resume the task exactly where it stopped and continue through to completion. Do not apologize for or mention this interruption.</system-reminder>";
|
|
const RESUME_AFTER_COMPACTION = "<system-reminder>The context was just compacted and the turn did not resume on its own. Continue the task from the compaction summary, exactly where it left off, through to completion. Do not restart from scratch, and do not apologize for or mention this.</system-reminder>";
|
|
|
|
const state = new Map(); // sessionID -> {errPending, compactPending, lastPrompt, consecutive, busy, deferred}
|
|
|
|
function getState(id) {
|
|
let s = state.get(id);
|
|
if (!s) {
|
|
s = { errPending: false, compactPending: false, lastPrompt: 0, consecutive: 0, erred: false,
|
|
lastRefusal: "", sameRefusal: 0 };
|
|
state.set(id, s);
|
|
}
|
|
return s;
|
|
}
|
|
|
|
async function log(msg) {
|
|
try { await appendFile(LOG, new Date().toISOString().slice(11, 19) + " " + msg + "\n"); } catch {}
|
|
}
|
|
|
|
function errText(error) {
|
|
if (!error || typeof error !== "object") return String(error ?? "");
|
|
const d = error.data && typeof error.data === "object" ? error.data : {};
|
|
return `${error.name ?? ""}: ${d.message ?? error.message ?? JSON.stringify(error).slice(0, 200)}`;
|
|
}
|
|
|
|
// True only if the LAST message of the session is the compaction boundary,
|
|
// the sign that opencode compacted then stopped without relaunching the turn.
|
|
// A normally finished assistant turn (task actually done) returns false, so a
|
|
// completed task is never relaunched. Unknown shape or error => false.
|
|
async function stuckAfterCompaction(client, sessionID) {
|
|
try {
|
|
const res = await client.session.messages({ path: { id: sessionID } });
|
|
const list = Array.isArray(res) ? res : res?.data ?? res?.messages ?? [];
|
|
if (!Array.isArray(list) || list.length === 0) return false;
|
|
const last = list[list.length - 1];
|
|
if (last?.info?.summary === true || last?.summary === true) return true;
|
|
const agent = last?.info?.agent ?? last?.agent;
|
|
if (typeof agent === "string" && agent.toLowerCase().includes("compact")) return true;
|
|
if (/"type"\s*:\s*"compaction"/.test(JSON.stringify(last))) return true;
|
|
return false;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function relaunch(client, sessionID, s, text, tag) {
|
|
s.lastPrompt = Date.now();
|
|
s.consecutive += 1;
|
|
await new Promise((r) => setTimeout(r, IDLE_DELAY_MS));
|
|
await log(`RELAUNCH ${tag} ${s.consecutive}/${MAX_CONSECUTIVE} (${sessionID.slice(0, 12)})`);
|
|
await client.session.promptAsync({
|
|
path: { id: sessionID },
|
|
body: { parts: [{ type: "text", text }] },
|
|
});
|
|
}
|
|
|
|
async function onIdle(client, sessionID, s) {
|
|
// nothing pending: a clean idle far from the last relaunch means real
|
|
// progress (duplicate idles right after a relaunch do not count, nor the idle
|
|
// of a turn that ended on an error, one no longer relaunched included)
|
|
const erred = s.erred;
|
|
s.erred = false;
|
|
if (!s.errPending && !s.compactPending) {
|
|
if (!erred && Date.now() - s.lastPrompt > THROTTLE_MS) {
|
|
s.consecutive = 0;
|
|
s.sameRefusal = 0;
|
|
}
|
|
return;
|
|
}
|
|
const wait = THROTTLE_MS - (Date.now() - s.lastPrompt);
|
|
if (wait > 0) {
|
|
// Too soon after the last relaunch, so the next one waits, and is not dropped: this
|
|
// idle can be the session's last event. On the reference box an error kept two
|
|
// seconds after a relaunch (09:02:30 UTC) was never relaunched, and nothing followed
|
|
// until opencode restarted an hour later (found in review, 2026-09-24).
|
|
if (!s.deferred) {
|
|
s.deferred = setTimeout(() => {
|
|
s.deferred = null;
|
|
if (s.busy) return; // it moved on meanwhile; its next idle decides
|
|
onIdle(client, sessionID, s).catch((e) => log("plugin internal error: " + String(e).slice(0, 200)));
|
|
}, wait + 50);
|
|
}
|
|
return;
|
|
}
|
|
if (s.consecutive >= MAX_CONSECUTIVE) {
|
|
await log(`STOP (${sessionID.slice(0, 12)}): ${MAX_CONSECUTIVE} relaunches without progress`);
|
|
s.errPending = false;
|
|
s.compactPending = false;
|
|
return;
|
|
}
|
|
|
|
// the error takes priority (a hard break); otherwise a stuck compaction
|
|
if (s.errPending) {
|
|
s.errPending = false;
|
|
await relaunch(client, sessionID, s, RESUME_AFTER_ERROR, "err");
|
|
return;
|
|
}
|
|
if (s.compactPending) {
|
|
s.compactPending = false;
|
|
if (await stuckAfterCompaction(client, sessionID)) {
|
|
await relaunch(client, sessionID, s, RESUME_AFTER_COMPACTION, "compact");
|
|
} else {
|
|
await log(`compaction OK, resumed on its own (${sessionID.slice(0, 12)}): no relaunch`);
|
|
}
|
|
}
|
|
}
|
|
|
|
const plugin = async ({ client }) => {
|
|
await log("auto-continue plugin loaded (v2: errors + compaction)");
|
|
return {
|
|
event: async ({ event }) => {
|
|
try {
|
|
if (event.type === "session.error") {
|
|
const { sessionID, error } = event.properties ?? {};
|
|
if (!sessionID) return;
|
|
const txt = errText(error);
|
|
if (EXCLUDE.some((p) => txt.toLowerCase().includes(p))) {
|
|
await log(`error EXCLUDED (${sessionID.slice(0, 12)}): ${txt.slice(0, 120)}`);
|
|
return;
|
|
}
|
|
const s = getState(sessionID);
|
|
s.erred = true;
|
|
// a count or an id that changes in the message still makes the same refusal
|
|
const refusal = error?.data?.isRetryable === false ? txt.replace(/\d+/g, "#") : "";
|
|
s.sameRefusal = !refusal ? 0 : refusal === s.lastRefusal ? s.sameRefusal + 1 : 1;
|
|
s.lastRefusal = refusal;
|
|
if (s.sameRefusal >= SAME_REFUSAL_MAX) {
|
|
s.errPending = false;
|
|
await log(`STOP (${sessionID.slice(0, 12)}): the same refusal ${s.sameRefusal} times in a row: ${txt.slice(0, 120)}`);
|
|
return;
|
|
}
|
|
s.errPending = true;
|
|
await log(`error retained (${sessionID.slice(0, 12)}): ${txt.slice(0, 120)}`);
|
|
return;
|
|
}
|
|
|
|
if (event.type === "session.compacted") {
|
|
const sessionID = event.properties?.sessionID;
|
|
if (!sessionID) return;
|
|
getState(sessionID).compactPending = true;
|
|
await log(`compaction detected (${sessionID.slice(0, 12)}): resume armed`);
|
|
return;
|
|
}
|
|
|
|
// the session's own state as opencode publishes it: a deferred relaunch fires
|
|
// only on a session that is still idle
|
|
if (event.type === "session.status") {
|
|
const s = state.get(event.properties?.sessionID);
|
|
if (s) s.busy = event.properties?.status?.type !== "idle";
|
|
return;
|
|
}
|
|
|
|
if (event.type === "session.idle") {
|
|
const sessionID = event.properties?.sessionID;
|
|
if (!sessionID) return;
|
|
const s = state.get(sessionID);
|
|
if (!s) return;
|
|
s.busy = false;
|
|
await onIdle(client, sessionID, s);
|
|
}
|
|
} catch (e) {
|
|
await log("plugin internal error: " + String(e).slice(0, 200));
|
|
}
|
|
},
|
|
};
|
|
};
|
|
|
|
export default plugin;
|