-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
94 lines (83 loc) · 3.13 KB
/
Copy pathindex.ts
File metadata and controls
94 lines (83 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Auto-resume Claude sessions past omp's intentional give-up on multi-hour
* Anthropic usage-limit blocks. omp's built-in retry (`retry.maxDelayMs`)
* deliberately fails fast rather than sleep through a 5h/7d reset window
* (see session/agent-session.ts's fail-fast-cap comment upstream); this
* extension picks up from there: confirms the block via a fresh usage
* report, waits for the reset, and injects a `continue` turn.
*
* Reactive-only by design — see
* docs/superpowers/specs/2026-07-16-omp-auto-resume-design.md.
*/
import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
import { evaluateBlock, type UsageReportLike } from "./predicate";
const RESUME_MARGIN_MS = 5_000;
export function toUsageReportLike(reports: unknown): UsageReportLike[] {
const list = Array.isArray(reports) ? reports : [];
return list.map((report: any) => ({
provider: report?.provider,
limits: (report?.limits ?? []).map((limit: any) => ({
windowId: limit?.scope?.windowId,
usedFraction: limit?.amount?.usedFraction,
resetsAt: limit?.window?.resetsAt,
tiered: Boolean(limit?.scope?.tier),
})),
}));
}
function fmtWait(ms: number): string {
const mins = Math.max(0, Math.round(ms / 60_000));
if (mins < 60) return `${mins}m`;
const h = Math.floor(mins / 60);
return `${h}h${mins % 60 ? ` ${mins % 60}m` : ""}`;
}
export default function (api: ExtensionAPI) {
let ctx: ExtensionContext | undefined;
const handledEpisodes = new Set<string>();
let timer: ReturnType<typeof setTimeout> | undefined;
function notify(message: string, level: "info" | "warning" | "error" = "info"): void {
ctx?.ui.notify(message, level);
void api.exec("notify-send", ["omp", message]).catch(() => {});
}
async function handleRetryEnd(): Promise<void> {
if (!ctx) return;
const authStorage = ctx.modelRegistry.authStorage;
if (typeof authStorage?.fetchUsageReports !== "function") return;
let rawReports: unknown;
try {
rawReports = await authStorage.fetchUsageReports({ signal: AbortSignal.timeout(5_000) });
} catch {
return;
}
const decision = evaluateBlock({
nowMs: Date.now(),
activeProvider: ctx.models.current()?.provider,
reports: toUsageReportLike(rawReports),
handledEpisodes,
});
if (!decision.act) return;
if (timer) clearTimeout(timer);
const waitMs = decision.resetsAt - Date.now() + RESUME_MARGIN_MS;
notify(`Claude usage limit hit — auto-resuming in ${fmtWait(waitMs)}`, "warning");
timer = setTimeout(() => void onTimerFire(decision.episodeKey), waitMs);
(timer as unknown as { unref?: () => void }).unref?.();
}
async function onTimerFire(episodeKey: string): Promise<void> {
timer = undefined;
handledEpisodes.add(episodeKey);
if (!ctx?.isIdle()) return; // user already active again — never inject over live work
notify("Resumed after Claude usage-limit wait", "info");
api.sendUserMessage("continue");
}
api.on("session_start", (_event, c) => {
ctx = c;
});
api.on("auto_retry_end", (event, c) => {
ctx = c;
if (event.success) return;
void handleRetryEnd();
});
api.on("session_shutdown", () => {
if (timer) clearTimeout(timer);
timer = undefined;
});
}