/** * Auto-handoff near the usage limit. * * Neither Claude Code nor Codex tells a hook how much of the plan's limit is * left, so the guard reads it where each tool does expose it: * * Claude Code the status line command receives `rate_limits.five_hour` / * `seven_day` / `spend_limit` `.used_percentage` (Pro and Max, * after the first reply). `specweave statusline` saves them per * session under ~/.specweave/usage/. * Codex every turn appends a `token_count` event with * `rate_limits.primary` / `secondary` `.used_percent` to the * rollout file the hook's `transcript_path` points at. * * The Stop hook (`specweave usage-guard`) acts once per session and usage * window when any window is at or past the threshold (95% by default). In the * default `suggest` mode it only tells the user, and the work goes on; in * `enforce` mode it stops the session and the agent runs `specweave handoff`. * When every full window resets within `waitUnder` minutes (30 by default) it * does neither: waiting for the reset costs less than moving the work. Under * the threshold it prints `{}`: no tokens, no files. * * It only asks inside a SpecWeave project (the hook's `cwd` is in one), since * `specweave handoff` has nothing to hand off anywhere else. A Codex plan with * credits keeps working past 100%, so it is asked only when the session's own * log shows under an hour of credits left at the rate they are being spent. * * Two more cases never steer the model. `mode: "checkpoint"` is for plans where * credits or a proxy keep working past 100%: only local checkpoints are saved. * Inside SpecWeave Studio (`SPECWEAVE_STUDIO_THREAD_ID` is set) Studio switches * provider between turns itself, so the hooks only save the checkpoint it reads. * * @module core/session/usage-guard */ export declare const DEFAULT_THRESHOLD = 95; /** When every full window resets sooner than this many minutes, waiting beats a handoff. */ export declare const DEFAULT_WAIT_UNDER_MINUTES = 30; /** Settings files without this version were written before 3.0.11, when the only mode stopped the session. */ export declare const SETTINGS_VERSION = 2; /** The shortest usage window; a session that hit the limit may hit it again after this. */ export declare const LIMIT_HIT_REARM_MS: number; export interface UsageWindow { /** "5-hour", "weekly", "spend" or "-minute". */ name: string; /** 0-100. */ percent: number; /** Unix seconds, when known. */ resetsAt?: number; } /** * `suggest`: at the threshold, tell the user once that a handoff is available and keep working. * `enforce`: at the threshold, stop once and hand off. * `checkpoint`: only save local checkpoints; usage never steers the model. */ export type AutoHandoffMode = 'suggest' | 'enforce' | 'checkpoint'; export declare const AUTO_HANDOFF_MODES: readonly AutoHandoffMode[]; export interface AutoHandoffSettings { at: number; /** Missing means `suggest`. Files written before 3.0.11 read as `suggest` unless they say `checkpoint`. */ mode?: AutoHandoffMode; /** Minutes. When every window at the threshold resets sooner, nothing is suggested or enforced; 0 turns the rule off. */ waitUnder?: number; version?: number; since?: string; /** Status line command that was there before `auto-handoff on`, restored by `off`. */ previousStatusLine?: unknown; } export declare function specweaveHome(home?: string): string; /** * The stored settings, with defaults filled in. A file written before 3.0.11 * (no `version`) had one mode that stopped the session at 90%; it now reads as * `suggest` at 95%, keeping `checkpoint` and any threshold the user chose. */ export declare function readSettings(home?: string): AutoHandoffSettings | undefined; /** Whether these settings let usage steer the model at all (suggest or enforce), not only save checkpoints. */ export declare function handsOff(settings: AutoHandoffSettings | undefined): boolean; /** Whether these settings stop the session and hand off at the threshold. */ export declare function enforces(settings: AutoHandoffSettings | undefined): boolean; /** * The Studio thread this hook runs in, when SpecWeave Studio started the provider session. * Any non-empty value counts: delegated worker ids carry `%` and `:` and must still * checkpoint instead of handing off. Only the checkpoint filename is sanitized. */ export declare function studioThreadId(env?: NodeJS.ProcessEnv): string | undefined; export declare function writeSettings(settings: AutoHandoffSettings | undefined, home?: string): void; /** Windows from Claude Code's status line input (`rate_limits`). */ export declare function claudeWindows(input: unknown): UsageWindow[]; /** Save what the status line saw, for the Stop hook of the same session. */ export declare function recordClaudeUsage(input: unknown, home?: string, now?: number): UsageWindow[]; /** Claude Code drops its own usage cache after an hour; so does the guard. */ export declare const CLAUDE_CACHE_MAX_AGE_MS: number; /** * Claude Code's own record of the plan usage: `cachedUsageUtilization` in * ~/.claude.json (or $CLAUDE_CONFIG_DIR/.claude.json), written whenever Claude * Code fetches the usage, in every kind of session: terminal, desktop, Remote * Control and `claude -p`. It is the reading for sessions that never run a * status line. Ignored when older than an hour or saved for another account. */ export declare function claudeCachedReading(opts?: { env?: NodeJS.ProcessEnv; home?: string; now?: number; }): UsageReading | undefined; /** Desktop samples arrive about every 15 minutes; an older one may miss a jump to the limit. */ export declare const DESKTOP_SAMPLE_MAX_AGE_MS: number; /** Where the Claude desktop app keeps its own files. */ export declare function desktopAppDir(home?: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): string; /** * The Claude desktop app's plan-usage samples, `plan-usage-history.json`: * `{ version: 2, samples: [{ t, org, u: { fh, sd } }] }`, 5-hour (`fh`) and * 7-day (`sd`) percentages per organization, written about every 15 minutes * while the app runs. It is the only reading desktop and Remote Control * sessions leave on disk. Undocumented, so best effort: only the newest sample * of this session's organization (CLAUDE_CODE_ORGANIZATION_UUID), and only * when it is under 20 minutes old. */ export declare function desktopUsageReading(opts?: { env?: NodeJS.ProcessEnv; home?: string; now?: number; platform?: NodeJS.Platform; }): UsageReading | undefined; /** * The freshest reading for a Claude Code session that runs no status line. * Desktop samples carry no reset times; a window's reset does not move until * it passes, so one still ahead in the usage cache is borrowed for it. */ export declare function claudeFallbackReading(opts?: { env?: NodeJS.ProcessEnv; home?: string; now?: number; platform?: NodeJS.Platform; }): UsageReading | undefined; /** What the newest `token_count` events in a Codex rollout file say about the plan. */ export interface CodexUsage { windows: UsageWindow[]; /** Credits (or an unlimited plan) keep Codex working after a window is full. */ credits: boolean; /** * Minutes the credit balance lasts at the rate this log shows it falling. * Undefined when the plan is unlimited or the log shows no fall to measure. */ creditMinutesLeft?: number; } /** Credit balances older than this say nothing about the current rate. */ export declare const CREDIT_BURN_WINDOW_MS: number; /** A Codex session with credits is asked to hand off when fewer minutes of credits are left. */ export declare const CREDIT_MINUTES_LOW = 60; /** * Windows and credits from the newest `token_count` event of the plan's own * limit in a Codex rollout file. Codex logs several limits in one session; a * later `gpt-reserve` record at 0% must not hide a plan window at 95%, so * another bucket is used only when no plan record is found. * * For a plan with a finite credit balance the scan goes on, back to an hour * before that record, to see how fast the balance is falling. It stops at a * top-up (a record with no credits, or with less than half of today's * balance): what was spent before one says nothing about what is left. */ export declare function codexUsage(transcriptPath: string): CodexUsage; /** Whether a Codex plan's credits will carry the session on: it has some, and they are not about to run out. */ export declare function codexCreditsLast(usage: CodexUsage): boolean; /** Windows from the newest `token_count` event in a Codex rollout file. */ export declare function codexWindows(transcriptPath: string): UsageWindow[]; export interface UsageReading { tool: 'Claude Code' | 'Codex'; /** Epoch milliseconds of the reading. */ at: number; windows: UsageWindow[]; /** Codex only: credits keep it working past a full window, so it is not asked to hand off while they last. */ credits?: boolean; /** Codex only: minutes of credits left at the rate the newest session log shows, when it shows one. */ creditMinutesLeft?: number; } /** The newest usage any Claude Code session's status line recorded. */ export declare function latestClaudeReading(home?: string): UsageReading | undefined; /** The rate limits in the newest Codex session log (~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl). */ export declare function latestCodexReading(home?: string): UsageReading | undefined; /** The fullest window that has not reset yet. */ export declare function fullest(windows: UsageWindow[], now?: number): UsageWindow | undefined; /** "25 min", "2 h 10 min", "4 days". */ export declare function minutesPhrase(minutes: number): string; /** * What the guard does about the usage it read: * `none` under the threshold, or usage never steers the model (checkpoint mode); * `wait` at the threshold, but every full window resets within `waitUnder` minutes; * `suggest` tell the user once that a handoff is available, keep working; * `enforce` stop once and hand off. * `resetMinutes` is when the last of the full windows resets, when every one of them says. */ export type UsageDecision = { kind: 'none'; } | { kind: 'wait' | 'suggest' | 'enforce'; window: UsageWindow; resetMinutes?: number; }; /** Minutes until every given window has reset, or undefined when one of them has no reset time. */ export declare function minutesUntilReset(windows: UsageWindow[], now?: number): number | undefined; export declare function usageDecision(settings: AutoHandoffSettings | undefined, windows: UsageWindow[], now?: number): UsageDecision; /** `creditMinutes`: a Codex plan that got this far on credits, with about that many minutes of them left. */ export declare function handoffInstruction(w: UsageWindow, creditMinutes?: number, resetMinutes?: number): string; /** The `suggest` mode note: the model tells the user once and does not stop on its own account. */ export declare function suggestionInstruction(w: UsageWindow, creditMinutes?: number, resetMinutes?: number): string; export interface GuardInput { session_id?: string; /** Where the session runs; both tools send it. */ cwd?: string; transcript_path?: string; stop_hook_active?: boolean; } export interface GuardOutput { /** Codex: block the stop; `reason` goes to the model. */ decision?: 'block'; reason?: string; /** * Claude Code: non-error context for the model; the turn continues so it can * act on it. A `decision: "block"` would show the user "Stop hook error". */ hookSpecificOutput?: { hookEventName: 'Stop'; additionalContext: string; }; /** Claude Code: a line shown to the user. */ systemMessage?: string; } /** * Stop-hook output. The first time a session is at or past the threshold in a * usage window, it keeps the agent going for one more reply: to tell the user * a handoff is available (`suggest`) or to hand off (`enforce`); otherwise `{}`. * Also `{}` when every full window resets within `waitUnder` minutes, outside * a SpecWeave project (a plain chat has nothing to hand off) and for a Codex * plan whose credits keep it working past the limit, until they are about to * run out. */ export declare function usageGuard(input: GuardInput, opts?: { home?: string; now?: number; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform; }): GuardOutput; /** One short status line: the fullest windows, e.g. "5-hour 42% ยท weekly 12%". */ export declare function usageSummary(windows: UsageWindow[]): string; /** * When a turn fails on the rate limit, Claude Code and Grok Build fire * `StopFailure` with `error: "rate_limit"`. It is the backstop for a session * that ran out before the Stop hook could ask for a handoff, and the only * signal Grok Build gives (it shows no usage percentage). Grok's hook input is * camelCase (`sessionId`, `workspaceRoot`), Claude Code's snake_case. */ export interface LimitHitInput { sessionId?: string; session_id?: string; cwd?: string; workspaceRoot?: string; error?: string; } /** * Minutes until a session that just hit the limit can go on: when the last * full window resets. The reading may predate the jump to 100%, so with no * window at the threshold the fullest one counts. Undefined when unknown. */ export declare function limitResetMinutes(windows: UsageWindow[], at: number, now?: number): number | undefined; /** * Where a rate-limited turn should hand off, or undefined when it should not: * auto-handoff is off or checkpoint-only, the session runs inside Studio, the * failure is not a rate limit, the limit resets within `waitUnder` minutes * (the session can wait it out), the session already wrote one in the last * five hours, or the directory is not a SpecWeave project. Both `suggest` and * `enforce` hand off here: the session cannot go on, so this is the last * moment to write the handoff. Writes its marker before returning, so a retry * storm hands off once. The marker is separate from the Stop hook's: a session * that was asked at the threshold and still ran out writes a fresh handoff. */ export declare function limitHitTarget(input: LimitHitInput, opts?: { home?: string; now?: number; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform; }): string | undefined; //# sourceMappingURL=usage-guard.d.ts.map