diff --git a/doc/connections/AI-CONNECTIONS.md b/doc/connections/AI-CONNECTIONS.md index 78b805215ee..c3340182e0f 100644 --- a/doc/connections/AI-CONNECTIONS.md +++ b/doc/connections/AI-CONNECTIONS.md @@ -351,9 +351,20 @@ same inline connection/reconnect controls as missing-account setup. Pending cards are deduplicated. Creating a repair card persists a blocked run classification that suppresses immediate and periodic generic retries until the responsible user repairs the connection. Unsupported providers and failures that could not create -a card retain their existing recovery path. Tool permission errors and provider quota failures do not +a card retain their existing recovery path. Typed provider authentication failures +and the runtime's `provider_invalid_credentials` code enter this same repair path. +Managed repair follows the run's recorded account attribution, including proxy +accounts whose driver reports an upstream provider. Unmanaged adoption requires +a compatible provider. Tool permission errors and provider quota failures do not request model authentication. +An exhausted provider allowance with typed `quota_exhausted` evidence and no +reported reset asks the user to review billing and usage, then retry. It does +not create an estimated cooldown or an automatic provider retry. The task links +to Apps to review the connected AI account. Rate limits without a reset retain +their default cooldown; allowance limits with a reported reset retain their +scheduled retry. Older untyped quota failures retain their existing recovery. + Pre-dispatch `configuration_incomplete` failures also show this card when every missing binding is a personal `user_secret_ref` for the same compatible AI provider. This includes a teammate who has no value for an onboarding diff --git a/packages/shared/src/types/execution-projection.ts b/packages/shared/src/types/execution-projection.ts index 75ae5e13121..88d5b54e055 100644 --- a/packages/shared/src/types/execution-projection.ts +++ b/packages/shared/src/types/execution-projection.ts @@ -165,7 +165,7 @@ export interface TaskInterruptionPresentation { nextRetryAt: string | null; canRetry: boolean; retryAction?: "move_forward"; - userAction: "approval" | "question" | "reconnect" | "assign_agent" | "choose_model" | "resume" | "budget" | "project_access" + userAction: "approval" | "question" | "reconnect" | "provider_billing" | "assign_agent" | "choose_model" | "resume" | "budget" | "project_access" /** Board confirms that a previous server, which can no longer report, stopped its workspace copyback. */ | "confirm_owner_stop" /** Board confirms that a run whose server restarted before it recorded the agent's process has stopped. */ diff --git a/server/src/__tests__/ai-auth-failure.test.ts b/server/src/__tests__/ai-auth-failure.test.ts index 575edb21263..d793d285cd6 100644 --- a/server/src/__tests__/ai-auth-failure.test.ts +++ b/server/src/__tests__/ai-auth-failure.test.ts @@ -13,6 +13,34 @@ const failure = (missingBindings: unknown, reason = "secret_binding_missing") => }); describe("personal AI credential preflight recovery", () => { + it.each(["startup", "turn"])("routes a typed %s authentication failure through the persisted reconnect request", phase => { + const run = { errorCode: "native_session_interrupted", resultJson: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "openai", phase, + category: "authentication", message: "Invalid API key", retryability: "requires_action", + } } }; + expect(isAiAuthenticationRepairable(run)).toBe(true); + expect(aiBindingForAuthRecovery("paperclip_runner", { provider: "codex" }, run)) + .toMatchObject({ provider: "openai" }); + expect(aiBindingForAuthRecovery("claude_local", {}, run)).toBeUndefined(); + expect(isAiAuthenticationBlocked({ ...run, livenessState: "failed" })).toBe(false); + expect(classifyRunLiveness({ ...run, runStatus: "failed", issue: null, authenticationRepairRequested: true })) + .toMatchObject({ livenessState: "blocked", nextAction: "Complete the connection request to continue this task" }); + }); + + it.each(["quota_exhausted", "permission", "rate_limit"])("does not reconnect for typed %s failures", category => { + expect(isAiAuthenticationRepairable({ errorCode: "native_session_interrupted", resultJson: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category, message: "Provider refused the request", retryability: "requires_action", + } } })).toBe(false); + }); + + it("does not offer model sign-in for sandbox authentication", () => { + expect(isAiAuthenticationRepairable({ resultJson: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "sandbox", phase: "startup", + category: "authentication", message: "Sandbox credentials rejected", retryability: "requires_action", + } } })).toBe(false); + }); + it.each(["user_secret_missing", "secret_inactive"])("offers Claude setup for %s without adopting another provider", errorCode => { const run = failure([{ ...missingClaudeKey, errorCode }]); expect(isAiAuthenticationRepairable(run)).toBe(true); diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts index 9ca870ca3d9..d09befed246 100644 --- a/server/src/__tests__/ai-connections.test.ts +++ b/server/src/__tests__/ai-connections.test.ts @@ -1716,9 +1716,10 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" }); it.each([ - ["anthropic", false], ["openai", false], ["anthropic", true], ["openai", true], - ] as const)("turns a %s auth failure into one card and resumes after repair (switch method: %s)", async (provider, switchMethod) => { - const userId = `auth-recovery-${provider}-${switchMethod}`; + ["anthropic", false, false], ["openai", false, false], ["anthropic", true, false], ["openai", true, false], + ["anthropic", false, true], ["openai", false, true], + ] as const)("turns a %s auth failure into one card and resumes after repair (switch method: %s, typed: %s)", async (provider, switchMethod, typed) => { + const userId = `auth-recovery-${provider}-${switchMethod}-${typed}`; const id = randomUUID(); const issueId = randomUUID(); const runId = randomUUID(); @@ -1729,10 +1730,21 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello" await db.insert(issues).values({ id: issueId, companyId, title: "Fix provider login", status: "in_progress", assigneeAgentId: id }); const account = await service.save(companyId, userId, { provider, method: "api_key", ownership: "personal", name: "Recovery account", apiKey: "fixture", agentIds: [id], allAgents: false }, "fixture-recovery-key"); const runtime = await prepareManagedAiRuntime(db, { companyId, agentId: id, responsibleUserId: userId, adapterType, binding: selectedBinding, config: {} }); - await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, status: "failed", errorCode: "acpx_auth_required", responsibleUserId: userId, + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: id, status: "failed", errorCode: typed ? "native_session_interrupted" : "acpx_auth_required", responsibleUserId: userId, + ...(typed ? { resultJson: { providerFailure: { schema: "paperclip.provider-failure.v1", provider, phase: "turn", + category: "authentication", message: "Invalid API key", retryability: "requires_action" } } } : {}), contextSnapshot: { issueId, aiConnection: { ...runtime.attribution, identity: runtime.identity } } }); await runtime.cleanup(); const intents = connectionIntentService(db); + if (typed) { + const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + await db.update(heartbeatRuns).set({ contextSnapshot: { ...failed.contextSnapshot, aiConnection: { + ...runtime.attribution, identity: runtime.identity, provider: provider === "openai" ? "anthropic" : "openai", + } } }).where(eq(heartbeatRuns.id, runId)); + expect(await intents.requestForRunAuthFailure(runId)).toBeNull(); + expect((await db.select().from(connectionGrants).where(eq(connectionGrants.id, account.grantId)))[0].status).toBe("active"); + await db.update(heartbeatRuns).set({ contextSnapshot: failed.contextSnapshot }).where(eq(heartbeatRuns.id, runId)); + } const card = await intents.requestForRunAuthFailure(runId); expect(card).toMatchObject({ state: "needs_user_action", service: provider }); expect((await intents.requestForRunAuthFailure(runId))?.interactionId).toBe(card!.interactionId); diff --git a/server/src/services/ai-auth-failure.test.ts b/server/src/services/ai-auth-failure.test.ts index a895d89ca9f..08892d1dab3 100644 --- a/server/src/services/ai-auth-failure.test.ts +++ b/server/src/services/ai-auth-failure.test.ts @@ -3,7 +3,7 @@ import { aiConnectionMetadataSchema, aiRoutingHarness, isAiConnectionCompatible import { aiBindingForAuthRecovery, isAiAuthenticationFailure } from "./ai-auth-failure.js"; describe("AI authentication failure recovery", () => { - it.each(["acpx_auth_required", "claude_auth_required", "codex_auth_required", "grok_auth_required", "adapter_auth_missing", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"])("recognizes %s", (code) => { + it.each(["acpx_auth_required", "claude_auth_required", "codex_auth_required", "grok_auth_required", "adapter_auth_missing", "provider_invalid_credentials", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"])("recognizes %s", (code) => { expect(isAiAuthenticationFailure(code)).toBe(true); }); it.each(["github_auth_required", "native_adopted_runner_authentication_timeout", "rate_limit", "adapter_failed", "permission_denied", undefined])("does not treat %s as model authentication", (code) => { diff --git a/server/src/services/ai-auth-failure.ts b/server/src/services/ai-auth-failure.ts index 45ded369115..20295ca25be 100644 --- a/server/src/services/ai-auth-failure.ts +++ b/server/src/services/ai-auth-failure.ts @@ -1,4 +1,4 @@ -import { AI_PROVIDERS, AI_CONNECTION_CAPABILITIES, isAiConnectionCompatible, type AiConnectionBinding, type AiProvider } from "@paperclipai/shared"; +import { AI_PROVIDERS, AI_CONNECTION_CAPABILITIES, isAiConnectionCompatible, readProviderFailure, type AiConnectionBinding, type AiProvider } from "@paperclipai/shared"; type AuthenticationFailure = { errorCode?: string | null; @@ -39,15 +39,29 @@ export function isAiConnectionConfigurationFailure(run: AuthenticationFailure): ); } -export function isAiAuthenticationRepairable(run: AuthenticationFailure): boolean { - return isAiAuthenticationFailure(run.errorCode) || isAiConnectionConfigurationFailure(run); +/** Driver names that identify the same account as the Connections provider. */ +const AUTHENTICATION_PROVIDERS = new Map([ + ["claude", "anthropic"], ["codex", "openai"], ["grok", "xai"], + ["gemini", "google"], ["antigravity", "google"], ["copilot", "github"], +]); + +function authenticationProvider(run: AuthenticationFailure): AiProvider | undefined { + const failure = readProviderFailure(record(run.resultJson)?.providerFailure); + if (failure?.category !== "authentication") return undefined; + return AI_PROVIDERS.find(provider => provider === failure.provider) ?? AUTHENTICATION_PROVIDERS.get(failure.provider); +} + +export function isAiAuthenticationRepairable(run: AuthenticationFailure, provider?: AiProvider): boolean { + const failedProvider = authenticationProvider(run); + if (provider && failedProvider && provider !== failedProvider) return false; + return Boolean(failedProvider) || isAiAuthenticationFailure(run.errorCode) || isAiConnectionConfigurationFailure(run); } /** Provider authentication signals only. Tool authorization and quotas need different repairs. */ export function isAiAuthenticationFailure(code: string | null | undefined): boolean { return Boolean(code && ( /^(acpx|claude|codex|grok|opencode|gemini|kimi|pi|cursor|copilot)_auth_required$/i.test(code) - || ["adapter_auth_missing", "authentication_required", "auth_required", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"].includes(code) + || ["adapter_auth_missing", "provider_invalid_credentials", "authentication_required", "auth_required", "refresh_token_reused", "refresh_token_expired", "refresh_token_invalidated"].includes(code) )); } @@ -63,8 +77,10 @@ export function aiBindingForAuthRecovery( ): AiConnectionBinding | undefined { if (failure?.errorCode === "configuration_incomplete" && !isAiConnectionConfigurationFailure(failure)) return undefined; const missingProvider = failure ? missingPersonalAiCredentialProvider(failure) : undefined; + const failedProvider = failure ? authenticationProvider(failure) : undefined; for (const provider of AI_PROVIDERS) { if (missingProvider && missingProvider !== provider) continue; + if (failedProvider && failedProvider !== provider) continue; for (const method of ["subscription", "api_key"] as const) { if (!AI_CONNECTION_CAPABILITIES[provider].methods[method]) continue; // Recovery presents a concrete sign-in method. A responsible-user binding diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index f008af33efc..599cf15f22d 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -13,7 +13,7 @@ import { isDeepStrictEqual } from "node:util"; import { logActivity } from "./activity-log.js"; import { aiConnectionService } from "./ai-connections.js"; import { aiConnectionBindingSchema, aiConnectionCatalogSlug, aiConnectionRouterBindingSchema, aiConnectionSourceSlug } from "@paperclipai/shared"; -import { aiBindingForAuthRecovery, isAiAuthenticationFailure, isAiAuthenticationRepairable } from "./ai-auth-failure.js"; +import { aiBindingForAuthRecovery, isAiAuthenticationRepairable } from "./ai-auth-failure.js"; import { and, eq, desc, isNull, notInArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { @@ -343,7 +343,7 @@ export function connectionIntentService(db: Db) { const [source] = await client.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.id, options.sourceRunId))); const taskKey = text(source?.contextSnapshot?.aiRouterTaskKey); const evidence = record(source?.contextSnapshot?.aiRouterSelection); - if (!source || !isAiAuthenticationFailure(source.errorCode) || source.status !== "failed" || evidence?.poolId !== router.connectionId || !taskKey) return null; + if (!source || !isAiAuthenticationRepairable(source) || source.status !== "failed" || evidence?.poolId !== router.connectionId || !taskKey) return null; const [pin] = await client.select().from(aiConnectionTaskPins).where(and(eq(aiConnectionTaskPins.companyId, companyId), eq(aiConnectionTaskPins.poolId, router.connectionId), eq(aiConnectionTaskPins.agentId, agentId), eq(aiConnectionTaskPins.taskKey, taskKey))); const binding = pin?.selection.binding; if (!pin || !binding || !aiBindingMatchesService(binding.provider, serviceSlug) || JSON.stringify(evidence.binding) !== JSON.stringify(binding)) return null; @@ -1537,6 +1537,9 @@ export function connectionIntentService(db: Db) { const binding = router ? managed?.binding : saved ?? aiBindingForAuthRecovery(agent.adapterType, agent.adapterConfig, run); if (!binding) return null; const attribution = record(run.contextSnapshot?.aiConnection); + // The recorded account is authoritative for routed/proxy connections: + // a driver's provider name can identify the upstream protocol instead. + if (!attribution && !isAiAuthenticationRepairable(run, binding.provider)) return null; if (attribution && attribution.provider !== binding.provider) return null; if ((saved || managed) && attribution && typeof attribution.identity === "string" && typeof attribution.connectionId === "string" && typeof attribution.grantId === "string") { await aiConnectionService(db).markAuthenticationFailed({ companyId: run.companyId, runId: run.id, agentId: run.agentId, diff --git a/server/src/services/heartbeat/retries.test.ts b/server/src/services/heartbeat/retries.test.ts index f5798b7555a..73ea5bcf0a4 100644 --- a/server/src/services/heartbeat/retries.test.ts +++ b/server/src/services/heartbeat/retries.test.ts @@ -86,6 +86,18 @@ describe("heartbeat retry module callbacks", () => { for (const callback of Object.values(deps.runDispatch)) expect(callback).not.toHaveBeenCalled(); }); + it("does not schedule provider work for a quota that needs account repair", async () => { + const database = guardedDatabase(); + const deps = callbacks(); + const run = { ...unitRun(), errorCode: "provider_quota", resultJson: { errorFamily: "provider_quota", + providerFailure: { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category: "quota_exhausted", message: "Check billing", retryability: "requires_action" } } } as Run; + const result = await extracted.createHeartbeatRetries(database.db, deps).scheduleBoundedRetryForRun(run, {} as Agent); + expect(result).toMatchObject({ outcome: "not_scheduled", issueId: "issue" }); + expect(database.access).not.toHaveBeenCalled(); + expect(deps.appendRunEvent).not.toHaveBeenCalled(); + }); + it.each(["missing_run", "missing_agent"] as const)("keeps %s lookup behavior and requests the full source result", async (outcome) => { const database = guardedDatabase(); const deps = callbacks(); diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.ts index fd7fdeefb83..828c4bbd06b 100644 --- a/server/src/services/heartbeat/retries.ts +++ b/server/src/services/heartbeat/retries.ts @@ -9,6 +9,7 @@ import { notifyStatusCardIssueChange } from "../status-card-notifications.js"; import { notifyScheduledRetryDispatch } from "../run-dispatch-notifications.js"; import { deriveTaskKeyWithHeartbeatFallback } from "./run-state.js"; import { infrastructureRetryDelayMs } from "../system-recovery-state.js"; +import { isProviderQuotaActionRequired } from "../provider-quota-reset.js"; import { WORKSPACE_VALIDATION_FAILURE_CODE, isWorkspaceValidationFailedRun, @@ -510,6 +511,9 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen preserveWakeContext?: boolean; }, ) { + if (isProviderQuotaActionRequired(run, opts?.now)) return { outcome: "not_scheduled" as const, + reason: "Review the provider account's billing and usage allowance before retrying.", + issueId: readNonEmptyString(run.contextSnapshot?.issueId) }; const preparation = parseObject(run.resultJson?.executionRecovery); if (typeof preparation.preparationSettledAt === "string" && await isInterruptedNativePreparation(db, run)) { const children = await db.select().from(heartbeatRuns).where(and( diff --git a/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts b/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts index 55ea60a445e..020d115662f 100644 --- a/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts +++ b/server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts @@ -1,8 +1,9 @@ import { randomUUID } from "node:crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; -import { agentProviderLimitCooldown } from "./native-startup-retry.js"; +import { agentProviderLimitCooldown, planNativeStartupRetry } from "./native-startup-retry.js"; const HOUR_MS = 60 * 60_000; const DAY_MS = 24 * HOUR_MS; @@ -74,6 +75,39 @@ describe("native provider limit cooldown", () => { .toMatchObject({ resetAt, resetReported: true, category: "quota_exhausted" }); }); + it("does not invent a reset for an account quota that needs billing action", async () => { + const agentId = await limitedAgent(new Date(Date.now() + HOUR_MS)); + const [prior] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)); + // A prior weekly reset must not resurrect a wait after a newer billing refusal. + await db.insert(heartbeatRuns).values({ ...prior, id: randomUUID(), startedAt: new Date(), finishedAt: new Date(), + resultJson: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category: "quota_exhausted", providerCode: "insufficient_quota", + message: "Check your plan and billing details.", retryability: "requires_action", + } } }); + expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() })).toBeNull(); + }); + + it("keeps the default cooldown for a rate limit without a reset", async () => { + const agentId = await limitedAgent(new Date(Date.now() + HOUR_MS)); + await db.update(heartbeatRuns).set({ resultJson: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup", + category: "rate_limit", message: "Try again later.", retryability: "unknown", + } } }).where(eq(heartbeatRuns.agentId, agentId)); + expect(await agentProviderLimitCooldown(db, { companyId, agentId, now: new Date() })) + .toMatchObject({ resetReported: false, category: "rate_limit" }); + }); + + it("never plans a startup retry for a billing refusal even when the caller allows retries", async () => { + const agentId = await limitedAgent(new Date(Date.now() + HOUR_MS)); + const plan = await planNativeStartupRetry({ db, binding: { companyId, agentId, runId: randomUUID() }, + attempt: 1, retryable: true, now: new Date(), failure: { + schema: "paperclip.provider-failure.v1", provider: "openai", phase: "startup", + category: "quota_exhausted", message: "Check your billing details.", retryability: "requires_action", + } }); + expect(plan).toEqual({ nextAttemptAt: null, providerCooldownAt: null }); + }); + it("re-checks a dated reset days away within one day", async () => { const agentId = await limitedAgent(new Date(Math.ceil((Date.now() + 3 * DAY_MS) / HOUR_MS) * HOUR_MS)); const now = new Date(); diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 2bac73feed7..d4847d5e6bc 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -16056,6 +16056,16 @@ describe("native session bounded recovery", () => { }); }); + it.each([false, true])("stops a billing refusal on its first attempt even with a confirmed runner exit (remote: %s)", remote => { + const failure = Object.defineProperty(sessionOpenFailure(startupFailure({ + category: "quota_exhausted", retryability: "requires_action", message: "Check billing and usage.", + })), "runnerExitConfirmed", { value: true }); + const code = nativeSessionFailureSourceCode(failure); + expect(nativeRemoteStartupRejectionCode(code, failure, remote)).toBe(NATIVE_PROVIDER_STARTUP_REJECTED); + expect(nativeSessionFailureDisposition(1, new Date(), code)) + .toMatchObject({ phase: "terminal_failure", nextAttemptAt: null }); + }); + it("keeps bounded same-run retries for a local startup failure without a definite permanent cause", () => { for (const fields of [ {}, @@ -16063,7 +16073,8 @@ describe("native session bounded recovery", () => { { category: "overloaded", retryability: "transient", httpStatus: 503 }, { category: "timeout", retryability: "transient", httpStatus: 504 }, { category: "rate_limit", httpStatus: 429 }, - { category: "quota_exhausted", retryability: "requires_action", providerCode: "usageLimitExceeded" }, + { category: "quota_exhausted", retryability: "requires_action", providerCode: "usageLimitExceeded", + retryAt: new Date(Date.now() + 60_000).toISOString() }, { category: "model_unavailable", retryability: "requires_action" }, { phase: "turn", category: "authentication", retryability: "requires_action" }, ]) { @@ -16139,7 +16150,8 @@ describe("native session bounded recovery", () => { ...fields }); const confirmed = (fields: Record) => Object.defineProperty(sessionOpenFailure(limit(fields)), "runnerExitConfirmed", { value: true, enumerable: false }); - for (const fields of [{ category: "rate_limit" }, { category: "quota_exhausted", retryability: "requires_action" }]) { + for (const fields of [{ category: "rate_limit" }, { category: "quota_exhausted", retryability: "requires_action", + retryAt: new Date(Date.now() + 60_000).toISOString() }]) { const first = confirmed(fields); expect(nativeSessionFailureSourceCode(first)).toBe("provider_session_open_rejected"); // The first refusal still retries the same run after the cooldown. diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 77f211b3507..f4eab528a35 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -19,6 +19,7 @@ import { NATIVE_CLEANUP_SETTLING_MESSAGE, NATIVE_COMPLETED_TURN_CLEANUP_MESSAGE, import { prepareCursorCloudRuntime } from "./cursor-cloud-runtime.js"; import { LocalRuntimeApiListenerClosedError, resolveLocalRuntimeApiUrl } from "../../runtime-api.js"; import { providerFailureFromError } from "../../vendor/paperclip-runner/index.js"; +import { isProviderQuotaActionRequired } from "../provider-quota-reset.js"; import { readProviderFailure } from "@paperclipai/shared"; import { nativeCancellationHasUnsettledOwner, notifyNativeCancellation, waitForNativeCancellation } from "./native-cancellation-delivery.js"; import { readClaimedNativeStopRecovery } from "./native-cancellation-request.js"; @@ -9163,8 +9164,10 @@ export const NATIVE_PROVIDER_STARTUP_REJECTED_ACTION = function deterministicProviderStartupFailure(error: unknown): boolean { const failure = providerFailureFromError(error); - return failure?.phase === "startup" && failure.retryability === "requires_action" - && ["authentication", "permission", "invalid_request"].includes(failure.category); + return failure?.phase === "startup" && ( + isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } }) + || failure.retryability === "requires_action" && ["authentication", "permission", "invalid_request"].includes(failure.category) + ); } /** The Runner transport proved the failed runner settled and its process exited. */ @@ -9214,9 +9217,9 @@ export function nativeStartupFailureSignature(failure: unknown): string | null { * startup error. Otherwise it ends at once with Retry. A deterministic * rejection never reaches here: it is already NATIVE_PROVIDER_STARTUP_REJECTED. * - * An exhausted provider allowance (a rate limit or quota) ends as a usage-limit - * hold instead: it passes by itself, so the hold retries the task at the reset - * like a limit reported on a turn, rather than waiting for a person's Retry. + * A rate limit or an allowance with a reported reset can end as a usage-limit + * hold, which retries the task at the reset like a limit reported on a turn. + * A quota with no reset is already classified as an action-required refusal. */ export function nativeRemoteStartupRejectionCode( sourceFailureCode: Code, diff --git a/server/src/services/native-runtime/native-startup-retry.integration.test.ts b/server/src/services/native-runtime/native-startup-retry.integration.test.ts index 7f420fc2c6b..56315052149 100644 --- a/server/src/services/native-runtime/native-startup-retry.integration.test.ts +++ b/server/src/services/native-runtime/native-startup-retry.integration.test.ts @@ -41,6 +41,7 @@ import { environmentRunnerIngressErrorData, JsonRpcCallError, PluginEnvironmentR import { accountRunCost } from "../run-cost-accounting.js"; import { settleUnrecoverableExecutions } from "../execution-recovery-resolution.js"; import { agentProviderLimitCooldown } from "./native-startup-retry.js"; +import { projectTaskInterruption } from "../task-interruption-presentation.js"; import { resolveLocalRuntimeApiUrl, runtimeApiInternals } from "../../runtime-api.js"; type SessionOpenStatus = "failed" | "rejected" | "indeterminate"; @@ -901,6 +902,24 @@ describe("native provider startup retry", () => { })).toEqual([]); }); + it("settles a startup billing refusal without scheduling another provider attempt", async () => { + const seeded = await seedRun(await createAgent()); + const failure = Object.defineProperty(sessionOpenFailure({ providerFailure: limitFailure({ + phase: "startup", category: "quota_exhausted", retryability: "requires_action", + message: "Check your plan and billing details.", + }) }), "runnerExitConfirmed", { value: true }); + await failStartup(seeded, failure); + const state = await read(seeded); + expect(state.coordinator).toMatchObject({ phase: "terminal_failure", recoveryState: "blocked", nextAttemptAt: null }); + expect(state.run.status).toBe("failed"); + expect(state.issue).toMatchObject({ status: "blocked", executionRunId: null }); + expect(projectTaskInterruption(state.issue, { run: state.run, action: state.action ?? undefined, + agent: { status: "idle", pauseReason: null }, paused: false, approval: false })) + .toMatchObject({ state: "waiting_for_user", userAction: "provider_billing", nextRetryAt: null }); + expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "startup-retry-test", runIds: [seeded.runId], + now: new Date(Date.now() + 10 * 60_000), deferIneligible: false })).toEqual([]); + }); + it("waits for the cooldown of a recent provider usage limit before retrying", async () => { const agentId = await createAgent(); const limitedAt = new Date(Date.now() - 5 * 60_000); diff --git a/server/src/services/native-runtime/native-startup-retry.ts b/server/src/services/native-runtime/native-startup-retry.ts index f645c54aaa8..1ce96c08656 100644 --- a/server/src/services/native-runtime/native-startup-retry.ts +++ b/server/src/services/native-runtime/native-startup-retry.ts @@ -4,7 +4,7 @@ import { heartbeatRuns, type Db } from "@paperclipai/db"; import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared"; import { logger } from "../../middleware/logger.js"; import { infrastructureRetryDelayMs, PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS } from "../system-recovery-state.js"; -import { parseProviderQuotaClockReset } from "../provider-quota-reset.js"; +import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "../provider-quota-reset.js"; /** Categories that report an exhausted account or request allowance. */ const PROVIDER_LIMIT_CATEGORIES = ["rate_limit", "quota_exhausted"]; @@ -18,6 +18,7 @@ type ProviderLimitEvidence = { resetAt: number; resetReported: boolean; category function limitEvidence(failure: ProviderFailure | null, observedAt: Date, sourceRunId: string | null): ProviderLimitEvidence | null { if (!failure || !PROVIDER_LIMIT_CATEGORIES.includes(failure.category)) return null; + if (isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } }, observedAt)) return null; const retryAt = failure.retryAt ? Date.parse(failure.retryAt) : Number.NaN; if (Number.isFinite(retryAt)) return { resetAt: retryAt, resetReported: true, category: failure.category, sourceRunId }; // ACP harnesses report the reset only in the provider's own wording. @@ -49,6 +50,7 @@ export async function agentProviderLimitCooldown(db: Db, input: { failure?: ProviderFailure | null; now: Date; }): Promise { + if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now)) return null; const now = input.now.getTime(); let latest = limitEvidence(input.failure ?? null, input.now, input.runId ?? null); const rows = await db @@ -77,7 +79,10 @@ export async function agentProviderLimitCooldown(db: Db, input: { for (const row of rows) { // The provider accepted work after this point, so its allowance was restored. if (row.status === "succeeded") break; - let recorded = limitEvidence(readProviderFailure(row.providerFailure), row.observedAt, row.id); + const failure = readProviderFailure(row.providerFailure); + // A newer billing refusal supersedes an older estimate or reported reset. + if (isProviderQuotaActionRequired({ resultJson: { providerFailure: failure } }, row.observedAt)) break; + let recorded = limitEvidence(failure, row.observedAt, row.id); if (recorded === null && PROVIDER_LIMIT_ERROR_CODES.includes(row.errorCode ?? "")) { const reset = row.retryNotBefore ? Date.parse(row.retryNotBefore) : Number.NaN; recorded = Number.isFinite(reset) @@ -108,6 +113,8 @@ export async function planNativeStartupRetry(input: { failure: ProviderFailure | null; now: Date; }): Promise<{ nextAttemptAt: Date | null; providerCooldownAt: Date | null }> { + if (isProviderQuotaActionRequired({ resultJson: { providerFailure: input.failure } }, input.now)) + return { nextAttemptAt: null, providerCooldownAt: null }; // Limit evidence only refines the schedule. A failed read must not stop the // failure from settling, so the retry falls back to plain backoff. const providerCooldownAt = await agentProviderLimitCooldown(input.db, { diff --git a/server/src/services/provider-quota-reset.test.ts b/server/src/services/provider-quota-reset.test.ts index 96b81178886..065b86e85f9 100644 --- a/server/src/services/provider-quota-reset.test.ts +++ b/server/src/services/provider-quota-reset.test.ts @@ -1,5 +1,20 @@ import { describe, expect, it } from "vitest"; -import { parseProviderQuotaClockReset } from "./provider-quota-reset.js"; +import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "./provider-quota-reset.js"; + +describe("provider account action", () => { + const failure = { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category: "quota_exhausted", message: "Check billing and usage.", retryability: "requires_action" }; + it("requires account repair for typed quota exhaustion even if an old recovery estimated a retry", () => { + expect(isProviderQuotaActionRequired({ resultJson: { providerFailure: failure, retryNotBefore: "2099-01-01T00:00:00Z" } })).toBe(true); + }); + it.each([ + { ...failure, category: "authentication" }, { ...failure, category: "rate_limit" }, + { ...failure, message: "You've hit your weekly limit · resets Nov 12, 6pm (UTC)" }, + { ...failure, retryAt: "2026-11-12T18:00:00.000Z" }, { ...failure, schema: "invalid" }, undefined, + ])("preserves other recovery and reported resets for %j", providerFailure => { + expect(isProviderQuotaActionRequired({ resultJson: { providerFailure } }, new Date("2026-11-10T20:00:00Z"))).toBe(false); + }); +}); describe("parseProviderQuotaClockReset", () => { it("reads a weekly limit's calendar reset, as Claude's ACP agent reports it", () => { diff --git a/server/src/services/provider-quota-reset.ts b/server/src/services/provider-quota-reset.ts index c158244175a..0e38ef58b6c 100644 --- a/server/src/services/provider-quota-reset.ts +++ b/server/src/services/provider-quota-reset.ts @@ -1,3 +1,14 @@ +import { readProviderFailure } from "@paperclipai/shared"; + +/** An exhausted account with no reported reset needs an account/billing repair. */ +export function isProviderQuotaActionRequired(run: { resultJson?: unknown } | null | undefined, observedAt = new Date()): boolean { + const result = run?.resultJson; + const failure = readProviderFailure(result && typeof result === "object" && !Array.isArray(result) + ? (result as Record).providerFailure : undefined); + return failure?.category === "quota_exhausted" && !failure.retryAt + && !parseProviderQuotaClockReset(failure.message, observedAt); +} + const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; const MONTH_NAMES = "jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"; const MAX_DATED_RESET_AHEAD_MS = 45 * 24 * 60 * 60_000; diff --git a/server/src/services/recovery/provider-failure-classification.test.ts b/server/src/services/recovery/provider-failure-classification.test.ts index e5bbc75b273..deeca9bdd2d 100644 --- a/server/src/services/recovery/provider-failure-classification.test.ts +++ b/server/src/services/recovery/provider-failure-classification.test.ts @@ -10,6 +10,15 @@ import { legacyExecutionNeedsReconciliation } from "../legacy-execution-recovery import { isConfigurationIncompleteFailedRun } from "../../modules/wake-queue/domain/values.js"; describe("classifyAdapterFailureForRecovery", () => { + it("keeps a typed billing quota out of continuation and provider-quota retry loops", () => { + const run = { errorCode: "provider_quota", error: "Provider quota exceeded", resultJson: { + errorFamily: "provider_quota", retryNotBefore: new Date(Date.now() + 60_000).toISOString(), + providerFailure: { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category: "quota_exhausted", message: "Check your plan and billing details.", retryability: "requires_action" }, + } }; + expect(classifyAdapterFailureForRecovery(run)).toBeNull(); + expect(classifyContinuationFailure(run as never)).toMatchObject({ kind: "non_retryable", maxAttempts: 0 }); + }); it("does not retry a permanently refused agent interaction delivery", () => { expect(classifyContinuationFailure({ errorCode: "agent_interaction_delivery_denied", resultJson: null } as never)) .toMatchObject({ kind: "non_retryable", maxAttempts: 0 }); diff --git a/server/src/services/recovery/run-result-read.test.ts b/server/src/services/recovery/run-result-read.test.ts index 7f937c36f0a..460f5e7afe2 100644 --- a/server/src/services/recovery/run-result-read.test.ts +++ b/server/src/services/recovery/run-result-read.test.ts @@ -45,6 +45,17 @@ describe.skipIf(!support.supported)("recovery result PostgreSQL projection", () expect(stored).toEqual(run); }); + it.each(["authentication", "quota_exhausted"])("retains typed %s evidence for native recovery", async category => { + const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category, message: "Account needs attention", retryability: "requires_action" }; + const { run, selected } = await read({ providerFailure, output: "private execution output" }, "native_session_interrupted"); + expect(selected.resultJson).toEqual({ providerFailure }); + const complete = { ...run, livenessState: "blocked" }; + const projected = { ...complete, resultJson: selected.resultJson }; + expect(isAiAuthenticationBlocked(projected)).toBe(isAiAuthenticationBlocked(complete)); + expect(classifyContinuationFailure(projected)).toMatchObject({ kind: "non_retryable", maxAttempts: 0 }); + }); + it.each(["adapter_failed", "provider_quota", "configuration_incomplete"])("retains arbitrary provider evidence for %s classification", async errorCode => { const now = new Date("2020-01-01T00:00:00Z"); const result = { providerSpecificField: { nestedResponse: "Rate limit exceeded. Try again after 2099-01-01T00:00:00Z" }, diff --git a/server/src/services/recovery/run-result-read.ts b/server/src/services/recovery/run-result-read.ts index 93c519a3273..0a91652890e 100644 --- a/server/src/services/recovery/run-result-read.ts +++ b/server/src/services/recovery/run-result-read.ts @@ -4,7 +4,7 @@ import { sql } from "drizzle-orm"; const recoveryResultKeys = [ "errorFamily", "workspaceValidation", "configurationIncomplete", "cancelledByActorType", "retryNotBefore", "transientRetryNotBefore", - "providerQuotaRetryNotBefore", "finalizationReasonCode", + "providerQuotaRetryNotBefore", "finalizationReasonCode", "providerFailure", ] as const; export const recoveryRunResultColumn = sql | null>` diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 7a92f5e196d..3a862ecfd62 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -131,7 +131,7 @@ import { isBoardOwnedBudgetBlock } from "../budget-block-ownership.js"; import { unadmittedChatWakeupCondition } from "../durable-chat-wakeup.js"; import { issueRecoveryActionService, SOURCE_TERMINAL_RESOLUTION } from "../issue-recovery-actions.js"; import { PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS } from "../system-recovery-state.js"; -import { parseProviderQuotaClockReset } from "../provider-quota-reset.js"; +import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "../provider-quota-reset.js"; import { hasUnverifiedNativeWorkspaceFinalizationOwner } from "../native-runtime/native-workspace-finalization-recovery-state.js"; import { legacyExecutionNeedsReconciliationWithEvidence, @@ -476,6 +476,7 @@ function readRecoveryRunErrorFamily(latestRun: LatestIssueRun) { } function isProviderQuotaRecovery(latestRun: LatestIssueRun) { + if (isProviderQuotaActionRequired(latestRun)) return false; if (latestRun?.errorCode === "provider_quota") return true; if (readRecoveryRunErrorFamily(latestRun) === "provider_quota") return true; if (latestRun?.errorCode !== "adapter_failed") return false; @@ -688,6 +689,7 @@ export function classifyAdapterFailureForRecovery( >, now = new Date(), ): AdapterFailureRecoveryClassification { + if (isProviderQuotaActionRequired(latestRun, now)) return null; // An engine prerequisite cannot be repaired by asking the same unavailable // engine to retry. Use the existing configuration-blocker path. if (latestRun.errorCode === "adapter_engine_unavailable" || latestRun.errorCode === "provider_tool_definition_invalid" || latestRun.errorCode === "native_provider_model_rejected") { @@ -781,7 +783,8 @@ export function classifyContinuationFailure( errorCode, }; } - if (isAiAuthenticationBlocked(latestRun) || (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode))) { + if (isAiAuthenticationBlocked(latestRun) || isProviderQuotaActionRequired(latestRun) + || (errorCode && NON_RETRYABLE_CONTINUATION_ERROR_CODES.has(errorCode))) { return { kind: "non_retryable", maxAttempts: 0, diff --git a/server/src/services/task-interruption-presentation.test.ts b/server/src/services/task-interruption-presentation.test.ts index 4e7ce6b2800..56c6348f733 100644 --- a/server/src/services/task-interruption-presentation.test.ts +++ b/server/src/services/task-interruption-presentation.test.ts @@ -367,6 +367,22 @@ it("preserves a provider explanation on a failed task without changing retry aut .not.toHaveProperty("providerFailure"); }); +it("asks for billing action for an exhausted provider quota without inventing a retry time", () => { + const failed = { ...run, errorCode: "native_provider_usage_limit", resultJson: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category: "quota_exhausted", providerCode: "insufficient_quota", message: "Check your plan and billing details.", + retryability: "requires_action", + } } }; + const input = { run: failed, agent, paused: false, approval: false }; + expect(projectTaskInterruption(issue, input)).toMatchObject({ state: "waiting_for_user", responsibility: "user", + userAction: "provider_billing", nextRetryAt: null }); + expect(projectTaskInterruption(issue, { ...input, paused: true })).toMatchObject({ userAction: "resume" }); + expect(projectTaskInterruption(issue, { ...input, approval: true })).toMatchObject({ userAction: "approval" }); + expect(projectTaskInterruption(issue, { ...input, run: { ...failed, resultJson: { providerFailure: { + ...failed.resultJson.providerFailure, retryAt: new Date(Date.now() + 60_000).toISOString(), + } } } })).not.toMatchObject({ userAction: "provider_billing" }); +}); + describe("task project-access interruption", () => { it("explains a project denial without offering a futile retry", () => { expect(projectTaskInterruption(issue, { run, agent, paused: false, approval: false })).toMatchObject({ diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index 9ed2a774f09..ab4d536ea91 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -12,6 +12,7 @@ import { unionAll } from "drizzle-orm/pg-core"; import { EXECUTION_RECONCILIATION_CAUSES, HEARTBEAT_RUN_STATUSES, readProviderFailure, type TaskInterruptionPresentation } from "@paperclipai/shared"; import { captureTaskInterruptionFailure } from "../sentry.js"; import { isAiAuthenticationBlocked } from "./ai-auth-failure.js"; +import { isProviderQuotaActionRequired } from "./provider-quota-reset.js"; import { readSystemRecovery } from "./system-recovery-state.js"; import { PROJECT_ACCESS_DENIED } from "./project-access-denial.js"; import { authorizationService } from "./authorization.js"; @@ -421,6 +422,8 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS return { ...base, state: "failed", canRetry: false, retryWait: { reason: "cleanup_quarantined", message: NATIVE_CLEANUP_SETTLING_MESSAGE } }; } + if (run.status === "failed" && isProviderQuotaActionRequired(run, new Date(now))) + return { ...base, responsibility: "user", state: "waiting_for_user", userAction: "provider_billing", canRetry: true }; return { ...base, state: "failed", canRetry: true, ...(projectAccess ? { projectAccess } : {}) }; } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 07bdf0d2e4b..5a1ad2a90ea 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -424,7 +424,7 @@ "packages/shared/src/types/email.ts": "556ff6a0dcefa01eb704d6d00d3b191de81ff4dc", "packages/shared/src/types/environment.ts": "62e62afcb3d5b7f246db1e8910a34fb0091f54db", "packages/shared/src/types/execution-continuation.ts": "5afe62afd227efa03ff847d8f73291c14707ab5b", - "packages/shared/src/types/execution-projection.ts": "75ae5e1312160fd9cec79e5234004221ef296ee6", + "packages/shared/src/types/execution-projection.ts": "88d5b54e05556a6e9482633f6d67786b20f98be4", "packages/shared/src/types/external-object.ts": "7a225e0f5a6777d449019a30530c858b753eb4c1", "packages/shared/src/types/feedback.ts": "c5eb31545c7f67c04ad9afd9db45a6b4774bcb35", "packages/shared/src/types/finance.ts": "5c2208c7950020f1005aa0dd86a1680c54dd4354", diff --git a/ui/src/components/ExecutionBlockerNotice.test.tsx b/ui/src/components/ExecutionBlockerNotice.test.tsx index dcf7aac9d16..76dee24d30e 100644 --- a/ui/src/components/ExecutionBlockerNotice.test.tsx +++ b/ui/src/components/ExecutionBlockerNotice.test.tsx @@ -38,6 +38,15 @@ describe("ordinary task interruption", () => { expect(container.querySelector("a, details, input, textarea")).toBeNull(); expect(container.textContent).not.toMatch(/service attention|process|receipt|workspace/i); }); + + it("offers account and billing repair instead of a quota countdown", async () => { + await render({ ...failed, state: "waiting_for_user", responsibility: "user", userAction: "provider_billing", + providerFailure: { schema: "paperclip.provider-failure.v1", provider: "openai", phase: "turn", + category: "quota_exhausted", message: "Check your plan and billing details.", retryability: "requires_action" } }); + expect(container.textContent).toContain("Check your provider account’s billing and usage allowance, then retry."); + expect(container.querySelector('a[href="/apps"]')?.textContent).toBe("Review AI account"); + expect(container.textContent).not.toMatch(/Trying again|retry automatically/); + }); it("does not report a failed attempt for a task the agent handed to a person", async () => { await render({ ...failed, responsibility: "user", state: "waiting_for_user", userAction: "unblock" }); expect(container.textContent).toBe(""); diff --git a/ui/src/components/ExecutionBlockerNotice.tsx b/ui/src/components/ExecutionBlockerNotice.tsx index 15f50a1bdf7..7bc7ce9be25 100644 --- a/ui/src/components/ExecutionBlockerNotice.tsx +++ b/ui/src/components/ExecutionBlockerNotice.tsx @@ -69,8 +69,12 @@ export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimi // Saved-work recovery is what the task waits for, so name it over the // generic automatic-retry line while keeping the provider explanation. return Retry : undefined}> + actions={<> + {presentation.userAction === "provider_billing" && } + {canRetry && presentation.canRetry && } + }> {presentation.state === "retry_scheduled" &&

{step ? `${step}. ${retryIn}` : "Paperclip will retry automatically."}

} + {presentation.userAction === "provider_billing" &&

Check your provider account’s billing and usage allowance, then retry.

} {isBudgetWait(presentation) &&

It is waiting for the budget to allow new work. Raise the budget in Costs.

}
; } diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsx index 42a41eec35e..b1cd253614a 100644 --- a/ui/src/pages/Inbox.tsx +++ b/ui/src/pages/Inbox.tsx @@ -415,7 +415,7 @@ export function FailedRunInboxRow({ : interruption?.state === "retry_scheduled" ? `Trying again in ${retrySeconds}s…` : interruption?.state === "failed" ? "Couldn’t finish this attempt. Your message is saved." : interruption?.state === "waiting_for_user" ? ({ - approval: "Approval required", question: "Respond to the pending question", reconnect: "Reconnect account", assign_agent: "Assign an agent", choose_model: "Choose a supported model", + approval: "Approval required", question: "Respond to the pending question", reconnect: "Reconnect account", provider_billing: "Review provider billing and usage", assign_agent: "Assign an agent", choose_model: "Choose a supported model", resume: "Work is paused", budget: "Budget limit reached", project_access: "Agent needs project access", confirm_owner_stop: "Confirm the previous server stopped",