A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI, feature] Park quota-blocked sessions until the provider reset and auto-resume (#2375)
Seth Karten2883a78431d2
diff --git a/packages/coding-agent/.changes/quota-park-until-reset.md b/packages/coding-agent/.changes/quota-park-until-reset.mdnew file mode 100644index 0000000000..15a03bad6a--- /dev/null+++ b/packages/coding-agent/.changes/quota-park-until-reset.md@@ -0,0 +1 @@+- Parked quota-blocked sessions now resume from a wake that survives aborts, restarts, and daemon-delivered wakes instead of clearing the park or stalling the resume, and a park no longer fails an active goal: the goal resumes with the task at the wake.diff --git a/packages/coding-agent/docs/settings.md b/packages/coding-agent/docs/settings.mdindex a0308dc836..e3f468c003 100644--- a/packages/coding-agent/docs/settings.md+++ b/packages/coding-agent/docs/settings.md@@ -208,6 +208,9 @@ When a provider requests a retry delay longer than `retry.provider.maxRetryDelay| `retry.provider.waitForUsage.maxDelayMs` | number | `300000` | Per-ping ceiling (5m) || `retry.provider.waitForUsage.maxAttempts` | number | `30` | Abort bound: maximum recovery pings || `retry.provider.waitForUsage.maxWaitMs` | number | `900000` | Abort bound: maximum total wait (15m) |+| `retry.provider.waitForUsage.pauseUntilReset` | boolean | `true` | Park quota-blocked sessions until the provider-reported reset instead of dying mid-task |+| `retry.provider.waitForUsage.maxPauseMs` | number | `86400000` | Abort bound: maximum single park (24h; clamped to 7d) |+| `retry.provider.waitForUsage.maxParks` | number | `8` | Abort bound: maximum parks per quota episode || `providerBackupModel` | string | none | Backup model ("provider/model-id" or bare id) used while the primary is quota-blocked or unavailable |The wait loop runs under the `retry.enabled` master switch: with retries@@ -226,6 +229,23 @@ waits never hang. When a reported reset time exceeds `maxWaitMs`, the wait givesup immediately with an informative error instead of pinging pointlessly — raise`maxWaitMs` to wait out long subscription windows.+When `pauseUntilReset` is on (the default) and such a reset is reported — e.g.+the ChatGPT-plan "Try again in ~7272 min" 429 — the session does not die+mid-task: it parks. The turn ends cleanly with a "parked until ..." status, the+park/resume transitions are recorded in the session log, and one durable+one-shot scheduled job (visible via `/cron`) wakes the session at the reset+time — or sooner when `maxPauseMs` caps the park. While parked the session+itself makes no model calls. The wake delivers an+in-context marker telling the model the pause happened and to continue the+interrupted task; that turn's single model call probes the quota. If the quota+is back, the task resumes with its context. If not, the session re-parks with+the newly reported reset, bounded by `maxPauseMs` per park and `maxParks` per+quota episode; when the budget is spent, it aborts exactly like the bounded+wait it replaced. Parks apply at the session level (subagents included), only+for quota failures with a provider-reported reset, and only when no backup+model took over; a `maxPauseMs` above 7 days is clamped. Set+`pauseUntilReset: false` to keep the pre-park behavior of failing immediately.+`providerBackupModel` routes failed turns to a user-defined backup modelinstead of waiting while the primary is quota-blocked or unavailable. It isdisabled by default: with no setting, behavior is unchanged and requests never@@ -249,7 +269,10 @@ available, authenticated model, the bounded wait runs instead."baseDelayMs": 1000,"maxDelayMs": 300000,"maxAttempts": 30,- "maxWaitMs": 900000+ "maxWaitMs": 900000,+ "pauseUntilReset": true,+ "maxPauseMs": 86400000,+ "maxParks": 8}}},diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 3d61fb836d..cfaec0af3a 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -122,8 +122,13 @@ import {loadContextTreeChildFromDisk,loadContextTreeChildrenFromDisk,} from "./context-tree.js";-import type { AgentCronJob, AgentRlmHeartbeatController, AgentRlmHeartbeatStatusUpdate } from "./cron-jobs.js";-import { normalizeHeartbeatDeliveryMode } from "./cron-jobs.js";+import {+ type AgentCronJob,+ AgentCronJobStore,+ type AgentRlmHeartbeatController,+ type AgentRlmHeartbeatStatusUpdate,+ normalizeHeartbeatDeliveryMode,+} from "./cron-jobs.js";import { DEFAULT_THINKING_LEVEL } from "./defaults.js";import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.js";import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";@@ -216,6 +221,7 @@ import {isPermanentProviderFailureKind,type ProviderWaitPolicy,parseProviderResetMs,+ providerParkDecision,providerRetryDelay,providerRetryPolicy,providerStreamFailureKind,@@ -1097,6 +1103,48 @@ const RLM_REGISTRY_ANSWER_PREVIEW_MAX_LENGTH = 200;/** Hard cap for labels carried into kernel roster entries (snapshots keep the full prompt). */const RLM_REGISTRY_LABEL_MAX_LENGTH = 200;+/** Session-log entry recorded when a quota-blocked session parks until the provider reset. */+const QUOTA_PARK_CUSTOM_ENTRY_TYPE = "provider_quota_park";+/** Session-log entry recorded when a parked session resumes, or when its wake could not resume it. */+const QUOTA_RESUME_CUSTOM_ENTRY_TYPE = "provider_quota_resume";+/** Label for the durable one-shot wake that resumes a parked session. */+const QUOTA_RESUME_CRON_LABEL = "quota-resume";+/**+ * In-context marker delivered on resume: tells the model the pause happened and+ * that it should continue the interrupted task. The same text is the prompt of+ * the durable wake job, so daemon-delivered resumes read identically.+ */+const QUOTA_RESUME_MARKER_TEXT =+ "<provider_quota_resumed>\n" ++ "The provider usage limit that paused this session has been reported as reset; this resume is automatic (retry.provider.waitForUsage.pauseUntilReset). Continue the interrupted task from where it stopped.\n" ++ "</provider_quota_resumed>";+/** Node caps timers at 2^31-1 ms; longer delays overflow setTimeout and fire after ~1ms. */+const MAX_TIMER_DELAY_MS = 2_147_483_647;+/** Retry delay for a wake that was consumed without resuming (refused admission, aborted probe). */+const QUOTA_WAKE_RETRY_DELAY_MS = 60_000;+/** Cap on those retries: a park that can never wake is dropped instead of parked forever. */+const QUOTA_WAKE_MAX_RETRIES = 3;++/** Data carried by a persisted provider_quota_park entry, used to restore a park after a restart. */+interface PersistedQuotaParkData {+ resumeAt: string;+ parkCount: number;+ jobId?: string;+}++function isPersistedQuotaParkData(value: unknown): value is PersistedQuotaParkData {+ if (!value || typeof value !== "object") {+ return false;+ }+ const record = value as Record<string, unknown>;+ return (+ typeof record.resumeAt === "string" &&+ typeof record.parkCount === "number" &&+ Number.isFinite(record.parkCount) &&+ (record.jobId === undefined || typeof record.jobId === "string")+ );+}+function noopRlmChildAbort(): void {}function noopRlmChildEventUnsubscribe(): void {}@@ -1477,6 +1525,32 @@ export class AgentSession {private _retryAuthFailureSources: AuthSourceToken[] = [];/** Ongoing wait-for-recovery state: pings issued and when the wait started. */private _providerWait: { attempts: number; startedAtMs: number } | undefined = undefined;+ /**+ * Quota park state: the session ended its turn because the provider-reported+ * usage reset was beyond the bounded wait, and a wake (in-process timer plus+ * a durable one-shot scheduled job) will resume the task automatically. While+ * parked the session itself makes no model calls.+ */+ private _quotaPark:+ | {+ /** Parks consumed in this quota episode; bounded by waitForUsage.maxParks. */+ parkCount: number;+ /** Wall-clock wake time for the current park. */+ resumeAtMs: number;+ /** Id of the durable one-shot wake job, when the session persists artifacts. */+ jobId?: string;+ /** Pending in-process wake timer for the current park. */+ timer?: ReturnType<typeof setTimeout>;+ /** True from the wake until the park state clears (the resume probe is running). */+ waking?: boolean;+ /** Wake re-arms consumed without a resume; bounded by QUOTA_WAKE_MAX_RETRIES. */+ wakeRetries?: number;+ }+ | undefined = undefined;+ /** Lazily built session-artifact store for durable quota-resume wake jobs. */+ private _quotaResumeJobStore: AgentCronJobStore | undefined = undefined;+ /** Wake jobs branch navigation cancelled, so returning to the parked branch can rebuild one. */+ private readonly _navigationCancelledWakeJobs = new Set<string>();/** Set while turns are routed to the user-configured backup model. */private _backupModel:| {@@ -1697,6 +1771,7 @@ export class AgentSession {this._pendingNextTurnMessages.push(createGoalContextMessage(this._goalState, "continuation"));}this._restoreLateIpythonSentAgentMessages();+ this._restoreQuotaPark();if (this._goalState.status === "active") {this._goalAccountingStartedAt = Date.now();}@@ -2344,6 +2419,12 @@ export class AgentSession {this._goalAbortInProgress = false;return;}+ // A live quota park owns the resume: the parked turn is the park's+ // pause, not the goal's death, so the goal survives until the wake+ // (or a spent park budget, which clears the park first) ends it.+ if (this._quotaPark !== undefined) {+ return;+ }this._finishGoalWithError(message.errorMessage || "Assistant response failed");}}@@ -4517,6 +4598,13 @@ export class AgentSession {this._providerWait = undefined;this._retryAuthFailureSources = [];}+ if (assistantMsg.stopReason === "aborted") {+ this._handleAbortedQuotaPark();+ } else if (assistantMsg.stopReason !== "error" && this._quotaPark) {+ // A parked session that completes a model call has its quota back:+ // clear the park (cancelling the pending wake) and resume the task.+ this._completeQuotaParkResume();+ }if (this._accountGoalUsageForAssistantMessage(assistantMsg)) {const message = createGoalContextMessage(this._goalState, "budget_limit");const normalized = normalizeMessageContent(message.content);@@ -4563,6 +4651,7 @@ export class AgentSession {this._finishActiveRetryWithFailure(msg);this._resolveRetry();if (!compactionWillRetry) {+ this._handleErroredQuotaParkProbe(msg);this._finishGoalForTerminalAssistantMessage(msg);// In serialized mode, agent-callable refine.run is serviced// at the shouldStopAfterTurn boundary, not here at agent_end.@@ -4974,6 +5063,12 @@ export class AgentSession {}this._scheduledAutoRefineTimers.clear();this._disarmAutonomousSubagentKeepAlive();+ // The in-process wake dies with the session; the durable one-shot job+ // stays so a restart can still restore the session and resume the task.+ if (this._quotaPark) {+ if (this._quotaPark.timer) clearTimeout(this._quotaPark.timer);+ this._quotaPark = undefined;+ }this._serializedPlanInFlight = undefined;this._serializedExplicitRefineOptions = undefined;this._pendingRequestedRefine = undefined;@@ -13084,6 +13179,22 @@ export class AgentSession {const resetMs = providerStreamFailureRetryAfterMs(message) ?? parseProviderResetMs(message.errorMessage);const decision = providerWaitDecision(pingAttempt, Date.now() - startedAtMs, resetMs, policy);if (decision.kind === "abort") {+ // A quota reset beyond the bounded wait parks the session instead of+ // dying mid-task: end the turn cleanly and resume at the reset time.+ if (reason === "usage" && decision.reason === "reset-too-far") {+ const park = providerParkDecision(this._quotaPark?.parkCount ?? 0, resetMs, policy);+ if (park.kind === "park") {+ return this._parkForQuotaReset(message, options, park.delayMs, decision.message, pingAttempt - 1);+ }+ }+ // A quota wait that gives up ends the episode's park: its wake has+ // already fired (or was never armed), so nothing else would resume it.+ // Future-scheduled parks survive; only stale post-wake parks clear.+ const stalePark = this._quotaPark;+ if (reason === "usage" && stalePark !== undefined && stalePark.resumeAtMs <= Date.now()) {+ this._cancelQuotaParkWake(stalePark);+ this._quotaPark = undefined;+ }this._markProviderAuthStaleForRetryFailure(message, options);const restoredModel = this._restorePrimaryModelAfterBackup();this._emit({@@ -13115,6 +13226,427 @@ export class AgentSession {);}+ /**+ * Park a quota-blocked session: end the failed turn cleanly, record the+ * parked transition in the session log, and schedule one wake (a durable+ * one-shot scheduled job plus an in-process timer) at the provider-reported+ * reset time. While parked the session makes no model calls; the wake+ * delivers the resume marker, whose first model call probes the quota.+ */+ private _parkForQuotaReset(+ message: AssistantMessage,+ options:+ | {+ markAuthStaleOnFailure?: boolean;+ authSourceTokens?: readonly AuthSourceToken[];+ }+ | undefined,+ pauseMs: number,+ abortMessage: string,+ parkedAttempt: number,+ ): boolean {+ const existing = this._quotaPark;+ if (existing !== undefined && existing.resumeAtMs > Date.now()) {+ // Already parked for this window (e.g. a heartbeat turn failed while+ // parked): keep the scheduled wake, consume no park, end the turn.+ this._finishQuotaParkedTurn(+ message,+ options,+ parkedAttempt,+ `Session is parked until ${new Date(existing.resumeAtMs).toISOString()} waiting for the provider usage reset; this turn ended without a retry: ${message.errorMessage || "unknown error"}`,+ );+ return false;+ }+ this._cancelQuotaParkWake(existing);+ const parkCount = (existing?.parkCount ?? 0) + 1;+ const resumeAtMs = Date.now() + pauseMs;+ const jobId = this._createQuotaResumeJob(resumeAtMs);+ const timer = this._scheduleQuotaResumeTimer(resumeAtMs);+ this._quotaPark = {+ parkCount,+ resumeAtMs,+ ...(jobId !== undefined ? { jobId } : {}),+ ...(timer !== undefined ? { timer } : {}),+ };+ this.sessionManager.appendCustomEntry(QUOTA_PARK_CUSTOM_ENTRY_TYPE, {+ resumeAt: new Date(resumeAtMs).toISOString(),+ parkCount,+ ...(jobId !== undefined ? { jobId } : {}),+ provider: message.provider,+ });+ this._finishQuotaParkedTurn(+ message,+ options,+ parkedAttempt,+ `${abortMessage}. Session parked until ${new Date(resumeAtMs).toISOString()} and will resume automatically (retry.provider.waitForUsage.pauseUntilReset): ${message.errorMessage || "unknown error"}`,+ );+ return false;+ }++ /** Shared park tail: mark auth stale, surface the parked status, end the retry and the turn. */+ private _finishQuotaParkedTurn(+ message: AssistantMessage,+ options:+ | {+ markAuthStaleOnFailure?: boolean;+ authSourceTokens?: readonly AuthSourceToken[];+ }+ | undefined,+ parkedAttempt: number,+ finalError: string,+ ): void {+ this._markProviderAuthStaleForRetryFailure(message, options);+ this._emit({ type: "auto_retry_end", success: false, attempt: parkedAttempt, finalError });+ this._retryAttempt = 0;+ this._providerWait = undefined;+ this._retryAuthFailureSources = [];+ this._resolveRetry();+ }++ /**+ * Durable wake: a one-shot scheduled job in this session's artifacts, so a+ * restart or closed worker still restores the session and delivers the+ * resume marker at the reset time. Best-effort: the in-process timer covers+ * live sessions when this cannot be persisted (e.g. in-memory sessions).+ */+ private _createQuotaResumeJob(resumeAtMs: number): string | undefined {+ const sessionFile = this.sessionFile;+ const store = this._quotaResumeStore();+ if (!sessionFile || !store) {+ return undefined;+ }+ try {+ const job = store.create({+ activeSessionId: this.sessionId,+ sessionId: this.sessionId,+ sessionFile,+ cwd: this.sessionManager.getCwd(),+ label: QUOTA_RESUME_CRON_LABEL,+ prompt: QUOTA_RESUME_MARKER_TEXT,+ scheduleText: `at ${new Date(resumeAtMs).toISOString()}`,+ runtimeKind: this._rlmDepth > 0 ? "subagent" : "top-level",+ });+ return job.id;+ } catch {+ return undefined;+ }+ }++ /** In-process wake for live sessions; unref'd so a parked session never holds the process open. */+ private _scheduleQuotaResumeTimer(resumeAtMs: number): ReturnType<typeof setTimeout> | undefined {+ const delayMs = Math.min(Math.max(resumeAtMs - Date.now(), 0), MAX_TIMER_DELAY_MS);+ const timer = setTimeout(() => {+ void this._resumeFromQuotaPark();+ }, delayMs);+ timer.unref();+ return timer;+ }++ /** Store over this session's artifact file; undefined for in-memory sessions. */+ private _quotaResumeStore(): AgentCronJobStore | undefined {+ if (this._quotaResumeJobStore) {+ return this._quotaResumeJobStore;+ }+ const artifactDir = this.sessionManager.getSessionArtifactDir();+ if (!this.sessionFile || !artifactDir) {+ return undefined;+ }+ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact(this.sessionId, artifactDir);+ this._quotaResumeJobStore = store;+ return store;+ }++ /**+ * Settle a park's durable wake: report a job the daemon already ran as+ * delivered (its prompt drives the resume) and leave it alone — rewriting a+ * completed job to cancelled would hide that the wake landed — cancel one+ * that has not run, and report a user cancellation as such. Anything else is+ * gone, leaving the in-process timer as the wake.+ */+ private _resolveQuotaResumeJob(jobId: string): "delivered" | "user-cancelled" | "cancelled" | "gone" {+ const job = this._findQuotaResumeJob(jobId);+ if (job?.status === "completed") {+ return "delivered";+ }+ if (job?.status === "cancelled") {+ return "user-cancelled";+ }+ const store = this._quotaResumeStore();+ if (!store) {+ return "gone";+ }+ try {+ return store.cancel(jobId) === undefined ? "gone" : "cancelled";+ } catch {+ return "gone";+ }+ }++ /** Cancel a park's pending wake: the in-process timer and the durable job. */+ private _cancelQuotaParkWake(+ park: { resumeAtMs: number; jobId?: string; timer?: ReturnType<typeof setTimeout> } | undefined,+ ): void {+ if (!park) return;+ if (park.timer) {+ clearTimeout(park.timer);+ park.timer = undefined;+ }+ if (park.jobId !== undefined) {+ this._resolveQuotaResumeJob(park.jobId);+ }+ park.jobId = undefined;+ }++ /**+ * Wake a parked session and deliver the resume marker: its first model call+ * probes the quota, resumes the interrupted task on success, and re-parks+ * with the newly reported reset on failure. The durable wake job and this+ * timer race for live sessions; whoever lands first owns the resume — the+ * job's prompt is the same marker text, so both paths read identically.+ */+ private async _resumeFromQuotaPark(): Promise<void> {+ const park = this._quotaPark;+ if (!park || park.waking || park.resumeAtMs > Date.now()) {+ return;+ }+ if (park.jobId !== undefined) {+ const resolved = this._resolveQuotaResumeJob(park.jobId);+ if (resolved === "delivered") {+ // The daemon dispatched the durable wake; its prompt drives the resume.+ park.waking = true;+ return;+ }+ if (resolved === "user-cancelled") {+ // The user cancelled the wake: honor it and drop the park.+ this._quotaPark = undefined;+ return;+ }+ // Cancelled by this timer or gone: the timer owns the resume.+ }+ park.waking = true;+ try {+ await this._queuePreparedPrompt("followUp", QUOTA_RESUME_MARKER_TEXT, undefined, {+ source: "internal",+ priority: "background",+ resumeIfIdle: true,+ });+ } catch {+ // A refused admission must not leave a park whose wake is gone: re-arm+ // it (bounded) so the session still resumes, or drop the park.+ park.waking = false;+ this._recoverQuotaParkWake("wake-failed");+ }+ }++ /**+ * An aborted turn is not evidence the quota is back. A wake whose resume+ * marker is still queued owns the resume, so an abort of some other turn must+ * not re-arm the wake under it; a wake this turn consumed re-arms instead.+ */+ private _handleAbortedQuotaPark(): void {+ const park = this._quotaPark;+ if (!park || (park.waking === true && this._hasQueuedQuotaResumeMarker())) {+ return;+ }+ park.waking = false;+ this._recoverQuotaParkWake("wake-aborted");+ }++ /** Whether the park wake's resume marker is still waiting in the session input queue. */+ private _hasQueuedQuotaResumeMarker(): boolean {+ return this._actionStore.unfinishedActions().some((action) => {+ if (action.payload.kind !== "turn" || action.lifecycle.state !== "queued") {+ return false;+ }+ const { text } = normalizeMessageContent(primaryDeliveryRecord(action).message.content);+ return text.includes(QUOTA_RESUME_MARKER_TEXT);+ });+ }++ /**+ * A turn that ended in a plain error after the wake's probe consumed the+ * marker is neither a resume nor a re-park: the park would sit `waking` with+ * no timer or job left, never resuming. Re-arm the wake (bounded) instead,+ * or drop the park once the retries are spent. A marker still queued owns+ * the resume, so an error from another turn must not re-arm under it.+ */+ private _handleErroredQuotaParkProbe(message: AssistantMessage): void {+ const park = this._quotaPark;+ if (message.stopReason !== "error" || park?.waking !== true || this._hasQueuedQuotaResumeMarker()) {+ return;+ }+ park.waking = false;+ this._recoverQuotaParkWake("wake-error");+ }++ /**+ * Wake re-arm for a park whose wake was consumed without resuming (refused+ * admission, aborted or errored probe turn). Bounded so a park that can+ * never wake ends instead of staying parked with no wake and no way to+ * resume.+ */+ private _recoverQuotaParkWake(outcome: "wake-failed" | "wake-aborted" | "wake-error"): void {+ const park = this._quotaPark;+ if (!park || park.waking || park.resumeAtMs > Date.now()) {+ return;+ }+ const retries = (park.wakeRetries ?? 0) + 1;+ if (retries > QUOTA_WAKE_MAX_RETRIES) {+ this._cancelQuotaParkWake(park);+ this._quotaPark = undefined;+ this.sessionManager.appendCustomEntry(QUOTA_RESUME_CUSTOM_ENTRY_TYPE, { outcome });+ return;+ }+ park.wakeRetries = retries;+ park.resumeAtMs = Date.now() + QUOTA_WAKE_RETRY_DELAY_MS;+ park.jobId = this._createQuotaResumeJob(park.resumeAtMs);+ park.timer = this._scheduleQuotaResumeTimer(park.resumeAtMs);+ // Record the replacement wake, or a restart reads the spent park entry,+ // drops the park, and leaves this retry job armed with no owner to cancel.+ this.sessionManager.appendCustomEntry(QUOTA_PARK_CUSTOM_ENTRY_TYPE, {+ resumeAt: new Date(park.resumeAtMs).toISOString(),+ parkCount: park.parkCount,+ ...(park.jobId !== undefined ? { jobId: park.jobId } : {}),+ });+ }++ private _findQuotaResumeJob(jobId: string): AgentCronJob | undefined {+ const store = this._quotaResumeStore();+ if (!store) {+ return undefined;+ }+ try {+ return store.list().find((job) => job.id === jobId);+ } catch {+ return undefined;+ }+ }++ /**+ * Durable wake for a restored park: reuse a job that can still fire and+ * recreate one that was cancelled (a navigation cancels the left-behind+ * leaf's wake) or removed, so a restored park never waits on a dead job.+ */+ private _restoreQuotaWakeJob(jobId: string | undefined, resumeAtMs: number): string | undefined | "user-cancelled" {+ if (jobId === undefined) {+ return this._createQuotaResumeJob(resumeAtMs);+ }+ const job = this._findQuotaResumeJob(jobId);+ if (job === undefined || job.status !== "cancelled") {+ // Not cancelled: still scheduled, or already delivered by the daemon.+ return jobId;+ }+ // A cancelled wake stays cancelled unless navigation cancelled it, which+ // frees the wake so returning to the parked branch can rebuild it.+ if (this._navigationCancelledWakeJobs.has(jobId)) {+ return this._createQuotaResumeJob(resumeAtMs);+ }+ return "user-cancelled";+ }++ /**+ * Rebuild the park for the branch this navigation selected. The old leaf's+ * wake is cancelled with it, so a parked leaf that was left behind cannot+ * resume its task on the selected branch.+ */+ private _reloadQuotaParkFromBranch(): void {+ const previous = this._quotaPark;+ this._quotaPark = undefined;+ if (previous?.timer) {+ clearTimeout(previous.timer);+ previous.timer = undefined;+ }+ if (previous?.jobId !== undefined) {+ // Only a wake this navigation actually cancels may be rebuilt on the way+ // back; a wake the user cancelled in /cron stays cancelled.+ if (this._resolveQuotaResumeJob(previous.jobId) === "cancelled") {+ this._navigationCancelledWakeJobs.add(previous.jobId);+ }+ }+ this._restoreQuotaPark();+ }++ /**+ * Restore the park this branch ended on: a restart (daemon or worker) leaves+ * waitForUsage.maxParks unbounded otherwise, because the park count would+ * start over at 1 each time. Parks recorded before the branch's last resume+ * entry are spent, and a park whose wake time has passed is left to the+ * durable wake job — only one that is still ahead re-arms the timer.+ */+ private _restoreQuotaPark(): void {+ const branch = this.sessionManager.getBranch();+ for (let index = branch.length - 1; index >= 0; index -= 1) {+ const entry = branch[index];+ if (entry.type !== "custom") {+ continue;+ }+ if (entry.customType === QUOTA_RESUME_CUSTOM_ENTRY_TYPE) {+ return;+ }+ if (entry.customType !== QUOTA_PARK_CUSTOM_ENTRY_TYPE || !isPersistedQuotaParkData(entry.data)) {+ continue;+ }+ const resumeAtMs = Date.parse(entry.data.resumeAt);+ if (!Number.isFinite(resumeAtMs) || resumeAtMs <= Date.now()) {+ return;+ }+ const jobId = this._restoreQuotaWakeJob(entry.data.jobId, resumeAtMs);+ if (jobId === "user-cancelled") {+ return;+ }+ if (jobId !== undefined && jobId !== entry.data.jobId) {+ // A rebuilt wake replaces the cancelled one: record it, so the next+ // restore reuses this job instead of arming another one beside it.+ this.sessionManager.appendCustomEntry(QUOTA_PARK_CUSTOM_ENTRY_TYPE, {+ resumeAt: entry.data.resumeAt,+ parkCount: entry.data.parkCount,+ jobId,+ });+ }+ this._quotaPark = {+ parkCount: entry.data.parkCount,+ resumeAtMs,+ ...(jobId !== undefined ? { jobId } : {}),+ timer: this._scheduleQuotaResumeTimer(resumeAtMs),+ };+ return;+ }+ }++ /**+ * A parked session completed a model call successfully: the quota is back.+ * Clear the park (cancelling any pending wake), record the resumed+ * transition, and — unless this success WAS the wake probe — deliver the+ * resume marker so the interrupted task continues right away.+ */+ private _completeQuotaParkResume(): void {+ const park = this._quotaPark;+ if (!park) return;+ // A wake the daemon already delivered owns the resume even when the timer+ // never observed it: the job's marker prompt is the continuation, so this+ // success must not queue a second one.+ const delivered = park.jobId !== undefined && this._resolveQuotaResumeJob(park.jobId) === "delivered";+ this._cancelQuotaParkWake(park);+ const wasWaking = park.waking === true || delivered;+ const restoredModel = this._restorePrimaryModelAfterBackup();+ this._quotaPark = undefined;+ this.sessionManager.appendCustomEntry(QUOTA_RESUME_CUSTOM_ENTRY_TYPE, {+ outcome: wasWaking ? "wake" : "early",+ ...(restoredModel ? { restoredModel } : {}),+ });+ if (!wasWaking) {+ void this._queuePreparedPrompt("followUp", QUOTA_RESUME_MARKER_TEXT, undefined, {+ source: "internal",+ priority: "background",+ resumeIfIdle: true,+ }).catch(() => {+ // The early-resume marker could not be queued; the park is cleared,+ // so a later quota failure parks again with a fresh schedule.+ });+ }+ }+/*** Return to the primary model after a backup-model retry, unless the user* switched models meanwhile. Returns the restored "provider/model-id"@@ -13170,6 +13702,11 @@ export class AgentSession {return this._retryPromise !== undefined;}+ /** True while the session is parked waiting out a provider-reported usage reset. */+ get isQuotaParked(): boolean {+ return this._quotaPark !== undefined;+ }+get hasAcceptedPromptInFlight(): boolean {return this._actionStore.unfinishedActions()@@ -13731,6 +14268,7 @@ export class AgentSession {this._ensureHarnessDigestContext();this._reloadGoalStateFromBranch({ monotonicTokens: Boolean(summaryText) });this._reloadRlmMaxDepthFromBranch();+ this._reloadQuotaParkFromBranch();this._invalidateQueuedPromptPreparation();await this._extensionRunner.emit({diff --git a/packages/coding-agent/src/core/provider-retry.ts b/packages/coding-agent/src/core/provider-retry.tsindex fc51d0d75f..813d4c8f7a 100644--- a/packages/coding-agent/src/core/provider-retry.ts+++ b/packages/coding-agent/src/core/provider-retry.ts@@ -180,6 +180,12 @@ export interface ProviderWaitPolicy {maxAttempts: number;/** Abort bound: maximum total wait. Default 15m. */maxWaitMs: number;+ /** Park sessions for provider-reported resets beyond maxWaitMs. Default true. */+ pauseUntilReset: boolean;+ /** Abort bound: maximum single park duration. Default 24h, clamped to 7d. */+ maxPauseMs: number;+ /** Abort bound: maximum parks per quota episode. Default 8. */+ maxParks: number;}export const DEFAULT_PROVIDER_WAIT_POLICY: ProviderWaitPolicy = {@@ -188,8 +194,44 @@ export const DEFAULT_PROVIDER_WAIT_POLICY: ProviderWaitPolicy = {maxDelayMs: 300_000,maxAttempts: 30,maxWaitMs: 900_000,+ pauseUntilReset: true,+ maxPauseMs: 86_400_000,+ maxParks: 8,};+/** Parks wake slightly after the reported reset so the window has actually rolled over. */+export const PROVIDER_RESUME_GRACE_MS = 30_000;++/** Upper clamp for maxPauseMs: one week per park, so long-horizon resets still get probed. */+export const MAX_PROVIDER_PAUSE_MS = 7 * 86_400_000;++export type ProviderParkDecision =+ | { kind: "park"; delayMs: number }+ | { kind: "none"; reason: "disabled" | "park-budget" | "no-reset" };++/**+ * Park decision after a quota failure whose provider-reported reset time exceeds+ * the bounded wait: the session ends the turn cleanly and wakes at the reset+ * (plus a small grace), capped at maxPauseMs. Only a provider-reported reset+ * parks: without one, the bounded wait keeps its existing abort behavior.+ */+export function providerParkDecision(+ parksUsed: number,+ resetMs: number | undefined,+ policy: Pick<ProviderWaitPolicy, "pauseUntilReset" | "maxPauseMs" | "maxParks">,+): ProviderParkDecision {+ if (!policy.pauseUntilReset) {+ return { kind: "none", reason: "disabled" };+ }+ if (parksUsed >= policy.maxParks) {+ return { kind: "none", reason: "park-budget" };+ }+ if (resetMs === undefined) {+ return { kind: "none", reason: "no-reset" };+ }+ return { kind: "park", delayMs: Math.min(resetMs + PROVIDER_RESUME_GRACE_MS, policy.maxPauseMs) };+}+export type ProviderWaitDecision =| { kind: "wait"; delayMs: number }| { kind: "abort"; reason: "attempts" | "duration" | "reset-too-far"; message: string };diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.tsindex e2aa28f77d..ce045cea66 100644--- a/packages/coding-agent/src/core/settings-manager.ts+++ b/packages/coding-agent/src/core/settings-manager.ts@@ -5,7 +5,7 @@ import { dirname, join } from "path";import lockfile from "proper-lockfile";import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";import { writeFileAtomicSync } from "../utils/atomic-file.js";-import type { ProviderWaitPolicy } from "./provider-retry.js";+import { MAX_PROVIDER_PAUSE_MS, type ProviderWaitPolicy } from "./provider-retry.js";const RECENT_MODELS_LIMIT = 20;export const DEFAULT_IDLE_EVICTION_MINUTES = 90;@@ -35,6 +35,9 @@ export interface ProviderWaitSettings {maxDelayMs?: number; // default: 300000 (per-ping ceiling, 5m)maxAttempts?: number; // default: 30 (abort bound: max pings)maxWaitMs?: number; // default: 900000 (abort bound: max total wait, 15m)+ pauseUntilReset?: boolean; // default: true - park quota-blocked sessions until the provider-reported reset+ maxPauseMs?: number; // default: 86400000 (abort bound: max single park, 24h; clamped to 7d)+ maxParks?: number; // default: 8 (abort bound: max parks per quota episode)}export interface ProviderRetrySettings {@@ -1094,6 +1097,11 @@ export class SettingsManager {maxDelayMs: bound(wait?.maxDelayMs, 300_000),maxAttempts: bound(wait?.maxAttempts, 30),maxWaitMs: bound(wait?.maxWaitMs, 900_000),+ pauseUntilReset: wait?.pauseUntilReset ?? true,+ // Very large parks are clamped to MAX_PROVIDER_PAUSE_MS instead of+ // silently waiting weeks for a stale reset.+ maxPauseMs: Math.min(bound(wait?.maxPauseMs, 86_400_000), MAX_PROVIDER_PAUSE_MS),+ maxParks: bound(wait?.maxParks, 8),};}diff --git a/packages/coding-agent/test/provider-retry.test.ts b/packages/coding-agent/test/provider-retry.test.tsindex 559935cb3f..3a7577bc15 100644--- a/packages/coding-agent/test/provider-retry.test.ts+++ b/packages/coding-agent/test/provider-retry.test.ts@@ -3,8 +3,10 @@ import { describe, expect, it } from "vitest";import {completeWithProviderRetry,DEFAULT_PROVIDER_WAIT_POLICY,+ type ProviderParkDecision,type ProviderWaitPolicy,parseProviderResetMs,+ providerParkDecision,providerRetryDelay,providerWaitClass,providerWaitDecision,@@ -75,6 +77,9 @@ const TEST_WAIT_POLICY: ProviderWaitPolicy = {maxDelayMs: 300_000,maxAttempts: 30,maxWaitMs: 900_000,+ pauseUntilReset: true,+ maxPauseMs: 86_400_000,+ maxParks: 8,};describe("providerWaitClass", () => {@@ -193,10 +198,28 @@ describe("providerWaitDecision", () => {maxDelayMs: 300_000,maxAttempts: 30,maxWaitMs: 900_000,+ pauseUntilReset: true,+ maxPauseMs: 86_400_000,+ maxParks: 8,});});});+describe("providerParkDecision", () => {+ // maxParks 0 disables parking outright, including the first park, and a park+ // is never guessed without a provider-reported reset.+ it.each<[number, number | undefined, Partial<ProviderWaitPolicy>, ProviderParkDecision]>([+ [0, 2 * 3_600_000, {}, { kind: "park", delayMs: 7_230_000 }],+ [0, 10 * 86_400_000, {}, { kind: "park", delayMs: 86_400_000 }],+ [0, 3_600_000, { pauseUntilReset: false }, { kind: "none", reason: "disabled" }],+ [8, 3_600_000, {}, { kind: "none", reason: "park-budget" }],+ [0, 3_600_000, { maxParks: 0 }, { kind: "none", reason: "park-budget" }],+ [0, undefined, {}, { kind: "none", reason: "no-reset" }],+ ])("uses %i parks at a reported reset of %s", (parksUsed, resetMs, overrides, expected) => {+ expect(providerParkDecision(parksUsed, resetMs, { ...TEST_WAIT_POLICY, ...overrides })).toEqual(expected);+ });+});+describe("parseProviderResetMs", () => {it("parses the real ChatGPT-plan usage-limit window", () => {expect(diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.tsindex 70d379c0e3..f7e51116ec 100644--- a/packages/coding-agent/test/settings-manager.test.ts+++ b/packages/coding-agent/test/settings-manager.test.ts@@ -210,4 +210,19 @@ describe("SettingsManager", () => {expect(manager.getTelemetryEnabled()).toBe(expected);});});++ // Park bounds are clamped like the other wait bounds: one week per park at most,+ // and non-finite park settings fall back to the defaults.+ describe("provider park bounds", () => {+ it("clamps park bounds and falls back to defaults on invalid values", () => {+ const wait = SettingsManager.inMemory({+ retry: { provider: { waitForUsage: { maxPauseMs: 365 * 86_400_000, maxParks: 99 } } },+ }).getProviderWaitSettings();+ expect([wait.pauseUntilReset, wait.maxPauseMs, wait.maxParks]).toEqual([true, 7 * 86_400_000, 99]);+ const invalid = SettingsManager.inMemory({+ retry: { provider: { waitForUsage: { maxPauseMs: Number.NaN, maxParks: -1 } } },+ }).getProviderWaitSettings();+ expect([invalid.maxPauseMs, invalid.maxParks]).toEqual([86_400_000, 0]);+ });+ });});diff --git a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts b/packages/coding-agent/test/suite/agent-session-retry-events.test.tsindex f71260ffc0..c4a29856ad 100644--- a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts+++ b/packages/coding-agent/test/suite/agent-session-retry-events.test.ts@@ -1,3 +1,5 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";import { AgentContinueError, type AgentEvent, type AgentTool, type ThinkingLevel } from "@earendil-works/pi-agent-core";import {type AssistantMessage,@@ -9,8 +11,9 @@ import {} from "@earendil-works/pi-ai";import { Type } from "typebox";import { afterEach, describe, expect, it, vi } from "vitest";+import { AgentCronJobStore } from "../../src/core/cron-jobs.js";import type { Settings } from "../../src/core/settings-manager.js";-import { createHarness, getAssistantTexts, type Harness } from "./harness.js";+import { createHarness, getAssistantTexts, getUserTexts, type Harness } from "./harness.js";function normalizeEventOrder(events: Harness["events"]): string[] {const normalized: string[] = [];@@ -741,6 +744,9 @@ describe("AgentSession retry and event characterization", () => {maxDelayMs?: number;maxAttempts?: number;maxWaitMs?: number;+ pauseUntilReset?: boolean;+ maxPauseMs?: number;+ maxParks?: number;}): Partial<Settings> {return {retry: {@@ -808,10 +814,8 @@ describe("AgentSession retry and event characterization", () => {expect(harness.session.isRetrying).toBe(false);});- it("aborts immediately when the provider-reported reset exceeds the wait bound", async () => {- const harness = await createHarness({- settings: waitSettings({ baseDelayMs: 1, maxDelayMs: 2, maxAttempts: 5, maxWaitMs: 1_000 }),- });+ it("aborts immediately when the provider-reported reset exceeds the wait bound and parking is disabled", async () => {+ const harness = await createHarness({ settings: parkSettings({ pauseUntilReset: false }) });harnesses.push(harness);harness.setResponses([quotaFailure({ retryAfterMs: 3_600_000 }), fauxAssistantMessage("unused")]);@@ -824,6 +828,299 @@ describe("AgentSession retry and event characterization", () => {expect(retryEnd[0]?.success).toBe(false);expect(retryEnd[0]?.finalError).toContain("maxWaitMs");expect(harness.session.isRetrying).toBe(false);+ expect(harness.session.isQuotaParked).toBe(false);+ });++ type QuotaParkInternals = {+ _quotaPark: { parkCount: number; resumeAtMs: number; jobId?: string; waking?: boolean } | undefined;+ _resumeFromQuotaPark: () => Promise<void>;+ _agentEventQueue: Promise<void>;+ };++ const quotaPark = (harness: Harness): QuotaParkInternals["_quotaPark"] =>+ (harness.session as unknown as QuotaParkInternals)._quotaPark;++ const parkSettings = (wait: Parameters<typeof waitSettings>[0]): Partial<Settings> =>+ waitSettings({ baseDelayMs: 1, maxDelayMs: 2, maxAttempts: 5, maxWaitMs: 1_000, ...wait });++ const parkHarness = async (settings: Partial<Settings>, persist = false): Promise<Harness> => {+ const harness = await createHarness({ persistSession: persist, settings });+ harnesses.push(harness);+ if (persist) harness.sessionManager.materializeSessionFile();+ return harness;+ };++ const farReset = (): AssistantMessage => quotaFailure({ retryAfterMs: 3_600_000 });+ const promptParked = async (harness: Harness, text: string, ends = 1): Promise<void> => {+ const parked = waitForRetryEnds(harness, ends);+ await harness.session.prompt(text);+ await parked;+ };++ const quotaEntries = (harness: Harness, customType: string): Array<Record<string, unknown>> =>+ harness.sessionManager+ .getEntries()+ .filter((entry) => entry.type === "custom" && entry.customType === customType)+ .map((entry) => (entry as { data?: Record<string, unknown> }).data ?? {});++ const assistantTurns = (harness: Harness): (() => Promise<AssistantMessage>) => {+ const buffered: AssistantMessage[] = [];+ const waiters: Array<(message: AssistantMessage) => void> = [];+ harness.session.subscribe((event) => {+ if (event.type !== "message_end" || event.message.role !== "assistant") return;+ const message = event.message as AssistantMessage;+ const waiter = waiters.shift();+ if (waiter) waiter(message);+ else buffered.push(message);+ });+ return async () => buffered.shift() ?? (await new Promise<AssistantMessage>((resolve) => waiters.push(resolve)));+ };++ const waitFor = (harness: Harness, ready: () => boolean): Promise<void> =>+ new Promise((resolve) => {+ const settle = (): void => {+ if (!ready()) return;+ unsubscribe();+ resolve();+ };+ const unsubscribe = harness.session.subscribe(settle);+ settle();+ });+ const waitForRetryEnds = (harness: Harness, count: number): Promise<void> =>+ waitFor(harness, () => harness.eventsOfType("auto_retry_end").length >= count);++ const fireQuotaWake = async (harness: Harness): Promise<void> => {+ const internals = harness.session as unknown as QuotaParkInternals;+ if (!internals._quotaPark) throw new Error("the session is not parked");+ internals._quotaPark.resumeAtMs = Date.now() - 1;+ await internals._resumeFromQuotaPark();+ };+ const wakeQuotaProbe = (harness: Harness): (() => Promise<AssistantMessage>) => {+ const turn = assistantTurns(harness);+ return () => fireQuotaWake(harness).then(turn);+ };++ const readQuotaWakeJob = (harness: Harness, jobId: string | undefined) =>+ (+ JSON.parse(+ readFileSync(join(harness.sessionManager.getSessionArtifactDir()!, "scheduled-jobs.json"), "utf-8"),+ ) as {+ jobs?: Array<{ id: string; status: string; prompt: string; schedule: { kind: string } }>;+ }+ ).jobs?.find((job) => job.id === jobId);+ const lastUserEntryId = (harness: Harness): string =>+ harness.sessionManager+ .getEntries()+ .filter((entry) => entry.type === "message" && entry.message.role === "user")+ .at(-1)!.id;++ it("parks a quota-blocked session until the provider reset and resumes automatically", async () => {+ const harness = await parkHarness(parkSettings({ maxPauseMs: 2_000 }), true);+ harness.setResponses([farReset(), farReset(), fauxAssistantMessage("recovered")]);+ await promptParked(harness, "do the work");+ expect([harness.session.isQuotaParked, harness.faux.state.callCount]).toEqual([true, 1]);+ const wakeJob = readQuotaWakeJob(harness, quotaPark(harness)?.jobId);+ expect([wakeJob?.status, wakeJob?.schedule.kind]).toEqual(["active", "once"]);+ expect(wakeJob?.prompt).toContain("<provider_quota_resumed>");+ await promptParked(harness, "second task", 2);+ expect([quotaPark(harness)?.parkCount, quotaPark(harness)?.jobId]).toEqual([1, wakeJob?.id]);+ await wakeQuotaProbe(harness)();+ expect(harness.session.isQuotaParked).toBe(false);+ expect(getUserTexts(harness).join("\n")).toContain("<provider_quota_resumed>");+ expect(quotaEntries(harness, "provider_quota_resume")[0]?.outcome).toBe("wake");+ expect(readQuotaWakeJob(harness, wakeJob?.id)?.status).toBe("cancelled");+ });++ it("re-parks at the wake with the newly reported reset and stops at the park bound", async () => {+ const harness = await parkHarness(parkSettings({ maxPauseMs: 2_000, maxParks: 2 }));+ harness.setResponses([farReset(), farReset(), farReset()]);+ await promptParked(harness, "/goal finish the task");+ const reparked = waitForRetryEnds(harness, 2);+ await fireQuotaWake(harness);+ await reparked;+ expect([harness.session.isQuotaParked, quotaPark(harness)?.parkCount]).toEqual([true, 2]);+ expect(harness.session.goalState.status).toBe("active");+ const spent = waitForRetryEnds(harness, 3);+ const goalErrored = waitFor(harness, () => harness.session.goalState.status === "error");+ await fireQuotaWake(harness);+ await spent;+ await goalErrored;+ expect(harness.session.isQuotaParked).toBe(false);+ expect(harness.eventsOfType("auto_retry_end").at(-1)?.finalError).toContain("maxWaitMs");+ });++ it("resumes early and cancels the scheduled wake when quota returns via another turn", async () => {+ const harness = await parkHarness(parkSettings({ maxPauseMs: 2_000 }), true);+ harness.setResponses([farReset(), fauxAssistantMessage("side answer"), fauxAssistantMessage("recovered")]);+ await promptParked(harness, "do the work");+ const wakeJobId = quotaPark(harness)?.jobId;+ const answered = assistantTurns(harness);+ await harness.session.prompt("side question");+ await answered();+ expect(harness.session.isQuotaParked).toBe(false);+ expect(getUserTexts(harness).join("\n")).toContain("<provider_quota_resumed>");+ expect(quotaEntries(harness, "provider_quota_resume")[0]?.outcome).toBe("early");+ expect(readQuotaWakeJob(harness, wakeJobId)?.status).toBe("cancelled");+ });++ it("stands down when the daemon already delivered the durable wake", async () => {+ const harness = await parkHarness(parkSettings({ maxPauseMs: 2_000 }), true);+ harness.setResponses([farReset(), fauxAssistantMessage("delivered")]);+ await promptParked(harness, "do the work");+ const jobId = quotaPark(harness)?.jobId;+ const artifactDir = harness.sessionManager.getSessionArtifactDir()!;++ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact(harness.sessionManager.getSessionId(), artifactDir);+ const [dispatch] = store.claimDue(new Date(Date.now() + 60_000));+ store.recordDispatchResult(dispatch!.id, { outcome: "ran" });+ await fireQuotaWake(harness);+ expect([quotaPark(harness)?.waking, harness.faux.state.callCount]).toEqual([true, 1]);+ expect(readQuotaWakeJob(harness, jobId)?.status).toBe("completed");+ });++ it("keeps the park, re-arms the wake, and restores the re-arm across a restart", async () => {+ const settings = parkSettings({ maxPauseMs: 60_000 });+ const abortedHarness = await parkHarness(settings, true);+ abortedHarness.setResponses([farReset(), fauxAssistantMessage("", { stopReason: "aborted" })]);+ await promptParked(abortedHarness, "do the work");+ const parkedAtMs = quotaPark(abortedHarness)?.resumeAtMs ?? 0;++ // An aborted probe is no evidence the quota is back: the park re-arms.+ const aborted = assistantTurns(abortedHarness);+ await fireQuotaWake(abortedHarness);+ expect((await aborted()).stopReason).toBe("aborted");+ const reArmed = quotaPark(abortedHarness);+ expect([reArmed?.waking, (reArmed?.resumeAtMs ?? 0) > parkedAtMs]).toEqual([false, true]);++ // The re-armed wake is recorded, so a restart restores the park with the retry job still owned.+ const restarted = await createHarness({ existingSessionFile: abortedHarness.session.sessionFile!, settings });+ harnesses.push(restarted);+ expect([restarted.session.isQuotaParked, quotaPark(restarted)?.parkCount]).toEqual([true, 1]);+ expect(readQuotaWakeJob(abortedHarness, reArmed?.jobId)?.status).toBe("active");+ restarted.setResponses([fauxAssistantMessage("recovered")]);+ await wakeQuotaProbe(restarted)();+ expect(readQuotaWakeJob(abortedHarness, reArmed?.jobId)?.status).toBe("cancelled");+ expect(restarted.session.isQuotaParked).toBe(false);++ // A refused admission re-arms too, and gives the park up once spent.+ const refusedHarness = await parkHarness(parkSettings({ maxPauseMs: 2_000 }));+ refusedHarness.setResponses([farReset(), fauxAssistantMessage("unused")]);+ await promptParked(refusedHarness, "do the work");+ const refusedAtMs = quotaPark(refusedHarness)?.resumeAtMs ?? 0;+ const pause = refusedHarness.session.acquireSessionInputPause();+ try {+ await fireQuotaWake(refusedHarness);+ expect(quotaPark(refusedHarness)?.resumeAtMs).toBeGreaterThan(refusedAtMs);+ for (let attempt = 0; attempt < 3; attempt += 1) await fireQuotaWake(refusedHarness);+ } finally {+ pause.release();+ }+ expect(refusedHarness.session.isQuotaParked).toBe(false);+ });++ it("re-arms the wake when the resume probe dies a plain error", async () => {+ const harness = await parkHarness(parkSettings({ maxPauseMs: 2_000 }), true);+ harness.setResponses([farReset(), structuredProviderFailure("invalid_request")]);+ await promptParked(harness, "do the work");+ const parkedAtMs = quotaPark(harness)?.resumeAtMs ?? 0;++ // The wake was consumed and the probe errored: without a re-arm the park+ // sits `waking` with no timer or job left, and the session never resumes.+ const probeEnded = waitFor(harness, () => harness.eventsOfType("agent_end").length >= 2);+ const errored = assistantTurns(harness);+ await fireQuotaWake(harness);+ expect((await errored()).stopReason).toBe("error");+ // The re-arm runs at the probe turn's terminal tail: settle the agent_end+ // event and the agent event queue before reading the park.+ await probeEnded;+ await (harness.session as unknown as QuotaParkInternals)._agentEventQueue;+ const reArmed = quotaPark(harness);+ expect([reArmed?.waking, (reArmed?.resumeAtMs ?? 0) > parkedAtMs]).toEqual([false, true]);+ expect(readQuotaWakeJob(harness, reArmed?.jobId)?.status).toBe("active");+ });++ it("restores a park across a restart, and honours a cancelled wake", async () => {+ const settings = parkSettings({ maxPauseMs: 60_000 });+ const harness = await parkHarness(settings, true);+ harness.setResponses([farReset()]);+ await promptParked(harness, "do the work");+ const sessionFile = harness.session.sessionFile!;++ // A restart rebuilds the park, and the wake still bounds the episode.+ const restarted = await createHarness({ existingSessionFile: sessionFile, settings });+ harnesses.push(restarted);+ expect([restarted.session.isQuotaParked, quotaPark(restarted)?.parkCount]).toEqual([true, 1]);+ restarted.setResponses([farReset()]);+ const reparked = waitForRetryEnds(restarted, 1);+ await fireQuotaWake(restarted);+ await reparked;+ expect(quotaPark(restarted)?.parkCount).toBe(2);++ // A wake the user cancelled stays cancelled, through a navigation and a restart.+ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact(+ restarted.sessionManager.getSessionId(),+ restarted.sessionManager.getSessionArtifactDir()!,+ );+ store.cancel(quotaPark(restarted)!.jobId!);+ await restarted.session.navigateTree(lastUserEntryId(restarted));+ await restarted.session.navigateTree(restarted.sessionManager.getLeafId()!);+ expect(restarted.session.isQuotaParked).toBe(false);+ const afterCancel = await createHarness({ existingSessionFile: sessionFile, settings });+ harnesses.push(afterCancel);+ expect(afterCancel.session.isQuotaParked).toBe(false);+ });++ it("moves the park with branch navigation", async () => {+ const settings = parkSettings({ maxPauseMs: 2_000 });+ const harness = await parkHarness(settings, true);+ harness.setResponses([farReset(), fauxAssistantMessage("recovered")]);+ await promptParked(harness, "do the work");+ const parkedLeaf = harness.sessionManager.getLeafId()!;+ await harness.session.navigateTree(lastUserEntryId(harness));+ expect([harness.session.isQuotaParked, harness.faux.state.callCount]).toEqual([false, 1]);++ await harness.session.navigateTree(parkedLeaf);+ expect(harness.session.isQuotaParked).toBe(true);+ const wakeJob = readQuotaWakeJob(harness, quotaPark(harness)?.jobId);+ expect(wakeJob?.status).toBe("active");++ const restarted = await createHarness({ existingSessionFile: harness.session.sessionFile!, settings });+ harnesses.push(restarted);+ expect(restarted.session.isQuotaParked).toBe(true);++ await wakeQuotaProbe(harness)();+ expect(harness.session.isQuotaParked).toBe(false);+ });++ it("preserves an active goal across a quota park and resumes its continuation", async () => {+ const harness = await parkHarness(parkSettings({ maxPauseMs: 2_000 }));+ const completeGoal = (): AssistantMessage => {+ harness.session.handleGoalHostRequest("goal.complete", {});+ return fauxAssistantMessage("Goal complete.");+ };+ harness.setResponses([farReset(), fauxAssistantMessage("recovered"), completeGoal]);+ await promptParked(harness, "/goal finish the task");+ // The parked turn is the park's pause, not the goal's death.+ expect([harness.session.isQuotaParked, harness.session.goalState.status]).toEqual([true, "active"]);+ const goalTurns = assistantTurns(harness);+ await fireQuotaWake(harness);+ await goalTurns(); // the wake's resume probe+ await goalTurns(); // the resumed goal-driven continuation completes the goal+ expect([harness.session.isQuotaParked, harness.session.goalState.status]).toEqual([false, "complete"]);+ });++ it("does not park while a backup model is configured and available", async () => {+ const harness = await createHarness({+ models: [{ id: "faux-1" }, { id: "faux-backup" }],+ settings: { providerBackupModel: "faux/faux-backup", ...parkSettings({}) },+ });+ harnesses.push(harness);+ harness.setResponses([quotaFailure({ retryAfterMs: 3_600_000 }), fauxAssistantMessage("backup answer")]);+ await harness.session.prompt("do the work");+ expect(harness.eventsOfType("auto_retry_start").map((event) => event.reason)).toEqual(["backup"]);+ expect(harness.session.isQuotaParked).toBe(false);});it("waits for an unavailable provider after quick retries exhaust", async () => {