Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore(agents): surface an exhausted Cursor usage limit as an actionable session notice (#6857)

Wolf Mermelstein3c297dadb3f2
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index e8929c3663..08d81ed7e0 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -72,7 +72,16 @@ vi.mock('../ui', () => ({
WorkingLine: (props: { label?: string }) => (
<div data-testid="working">{props.label}</div>
),
- ActionLine: (props: { label: string }) => <div>{props.label}</div>,
+ ActionLine: (props: { label: string }) => (
+ <div data-testid="action-line">{props.label}</div>
+ ),
+ FailureNoticeCard: (props: {
+ notice: { title: string; body: string; link?: { url: string } | null };
+ }) => (
+ <div data-link={props.notice.link?.url} data-testid="failure-notice">
+ {props.notice.title}
+ </div>
+ ),
ToolGroup: (props: {
count: number;
active: boolean;
@@ -573,3 +582,48 @@ describe('Message prompt attribution', () => {
expect(view.getByTestId('bubble')).toBeTruthy();
});
});
+
+describe('Message failed turns', () => {
+ it('reads an opaque failure as an action line carrying the runtime message', () => {
+ const view = render(() => (
+ <Message
+ message={message([], {
+ kind: 'failed',
+ message: 'Internal error: something broke',
+ })}
+ inFlight={false}
+ />
+ ));
+ expect(view.getByTestId('action-line').textContent).toContain(
+ 'Internal error: something broke'
+ );
+ expect(view.queryByTestId('failure-notice')).toBeNull();
+ });
+
+ it("shows a classified failure as a notice card, not the runtime's message", () => {
+ const view = render(() => (
+ <Message
+ message={message([], {
+ kind: 'failed',
+ message: 'Cursor usage limit reached. Raise the limit.',
+ notice: {
+ kind: 'provider_usage_limit',
+ title: 'Cursor usage limit reached',
+ body: 'Raise the spending limit in your Cursor dashboard.',
+ link: {
+ label: 'Manage Cursor usage',
+ url: 'https://www.cursor.com/dashboard?tab=settings',
+ },
+ },
+ })}
+ inFlight={false}
+ />
+ ));
+ const notice = view.getByTestId('failure-notice');
+ expect(notice.textContent).toBe('Cursor usage limit reached');
+ expect(notice.dataset.link).toBe(
+ 'https://www.cursor.com/dashboard?tab=settings'
+ );
+ expect(view.queryByTestId('action-line')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index a2be2b8aac..afb69cfdeb 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -12,6 +12,7 @@
import { useUserId } from '@core/context/user';
import { idToDisplayName } from '@core/user/util';
import { messageSendMotion } from '@core/util/message-send-motion';
+import { openExternalUrl } from '@core/util/url';
import type {
FoldedMessage,
MessagePart,
@@ -24,6 +25,7 @@ import { thoughtIsStreaming } from '../state/thought-streaming';
import { segmentParts } from '../state/tool-groups';
import {
ActionLine,
+ FailureNoticeCard,
isToolActive,
Thought,
ToolGroup,
@@ -266,9 +268,7 @@ export function Message(props: {
}) {
const inFlight = () => props.inFlight;
const failure = () =>
- props.message.stop?.kind === 'failed'
- ? props.message.stop.message
- : undefined;
+ props.message.stop?.kind === 'failed' ? props.message.stop : undefined;
return (
<Show
@@ -315,14 +315,27 @@ export function Message(props: {
session, like a model change or a stop — so it reads as one,
at the foot of whatever the agent managed to say first. The
line says what to do about it; the runtime's own account of
- what happened is the detail. */}
+ what happened is the detail. A failure the runtime wrote in the
+ person's terms is theirs to act on, so it gets a card instead. */}
<Show when={failure()}>
- {(message) => (
- <ActionLine
- label={`${TURN_FAILED_LABEL} — ${message()}`}
- detail={message()}
- failed
- />
+ {(failed) => (
+ <Show
+ when={failed().notice}
+ fallback={
+ <ActionLine
+ label={`${TURN_FAILED_LABEL} — ${failed().message}`}
+ detail={failed().message}
+ failed
+ />
+ }
+ >
+ {(notice) => (
+ <FailureNoticeCard
+ notice={notice()}
+ onOpenLink={openExternalUrl}
+ />
+ )}
+ </Show>
)}
</Show>
</div>
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index cc217be8c2..975565c047 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -36,6 +36,7 @@ import {
CountSummary,
DiffChanges,
ElicitationForm,
+ FailureNoticeCard,
PierreDiff,
QuestionAnswers,
type QuoteInsert,
@@ -1081,6 +1082,21 @@ export default function AgentUiGallery() {
/>
</Item>
+ <Item label="FailureNoticeCard">
+ <FailureNoticeCard
+ notice={{
+ kind: 'provider_usage_limit',
+ title: 'Cursor usage limit reached',
+ body: "Your Cursor account has no background-agent budget left, so this message wasn't sent. Raise the spending limit in your Cursor dashboard, then send it again.",
+ link: {
+ label: 'Manage Cursor usage',
+ url: 'https://www.cursor.com/dashboard?tab=settings',
+ },
+ }}
+ onOpenLink={(url) => window.open(url, '_blank', 'noopener')}
+ />
+ </Item>
+
<Item label="ToolCard">
<ToolCard
title="Shell"
diff --git a/apps/web/src/features/block-agent/ui/FailureNoticeCard.test.tsx b/apps/web/src/features/block-agent/ui/FailureNoticeCard.test.tsx
new file mode 100644
index 0000000000..b613ab8f38
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/FailureNoticeCard.test.tsx
@@ -0,0 +1,57 @@
+/** @vitest-environment jsdom */
+
+import type { FailureNotice } from '@service-agent-fold/generated/types';
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { FailureNoticeCard } from './FailureNoticeCard';
+
+afterEach(cleanup);
+
+const usageLimit: FailureNotice = {
+ kind: 'provider_usage_limit',
+ title: 'Cursor usage limit reached',
+ body: 'Raise the spending limit in your Cursor dashboard, then send it again.',
+ link: {
+ label: 'Manage Cursor usage',
+ url: 'https://www.cursor.com/dashboard?tab=settings',
+ },
+};
+
+describe('FailureNoticeCard', () => {
+ it('shows the title and body the runtime wrote for the person', () => {
+ const { getByText } = render(() => (
+ <FailureNoticeCard notice={usageLimit} onOpenLink={() => {}} />
+ ));
+
+ expect(getByText('Cursor usage limit reached')).toBeTruthy();
+ expect(
+ getByText(
+ 'Raise the spending limit in your Cursor dashboard, then send it again.'
+ )
+ ).toBeTruthy();
+ });
+
+ it('opens the link through the caller, with its label as the button', () => {
+ const onOpenLink = vi.fn();
+ const { getByRole } = render(() => (
+ <FailureNoticeCard notice={usageLimit} onOpenLink={onOpenLink} />
+ ));
+
+ fireEvent.click(getByRole('button', { name: 'Manage Cursor usage' }));
+
+ expect(onOpenLink).toHaveBeenCalledWith(
+ 'https://www.cursor.com/dashboard?tab=settings'
+ );
+ });
+
+ it('offers no button when the notice has nowhere to go', () => {
+ const { queryByRole } = render(() => (
+ <FailureNoticeCard
+ notice={{ ...usageLimit, link: null }}
+ onOpenLink={() => {}}
+ />
+ ));
+
+ expect(queryByRole('button')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-agent/ui/FailureNoticeCard.tsx b/apps/web/src/features/block-agent/ui/FailureNoticeCard.tsx
new file mode 100644
index 0000000000..29ad60aca2
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/FailureNoticeCard.tsx
@@ -0,0 +1,58 @@
+/**
+ * A turn failure the person can act on, as a card: what happened, what to do,
+ * and where to do it.
+ *
+ * The runtime classified the failure (a spent Cursor budget, say) and wrote
+ * it in the person's terms, so this shows it as an instruction — the same
+ * card shape as a permission request, in the failure ink — rather than as the
+ * quiet rule an opaque runtime error gets.
+ */
+
+import ArrowSquareOut from '@phosphor/arrow-square-out.svg';
+import WarningCircle from '@phosphor/warning-circle.svg';
+import type { FailureNotice } from '@service-agent-fold/generated/types';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+export interface FailureNoticeCardProps {
+ notice: FailureNotice;
+ /** Follows the notice's link; wired to the app's external-url handling. */
+ onOpenLink: (url: string) => void;
+}
+
+export function FailureNoticeCard(props: FailureNoticeCardProps) {
+ return (
+ <section
+ aria-label={props.notice.title}
+ class="min-w-0 overflow-hidden rounded-xl border border-edge-muted bg-panel text-ink"
+ >
+ <div class="flex items-start gap-3 px-4 pt-4">
+ <div class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-failure-bg text-failure">
+ <WarningCircle class="size-4" />
+ </div>
+ <div class="min-w-0 flex-1">
+ <div class="text-sm font-medium">{props.notice.title}</div>
+ <p class="mt-0.5 text-xs leading-5 text-ink-muted [overflow-wrap:anywhere]">
+ {props.notice.body}
+ </p>
+ </div>
+ </div>
+ <div class="p-3">
+ <Show when={props.notice.link}>
+ {(link) => (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ class="gap-1.5"
+ onClick={() => props.onOpenLink(link().url)}
+ >
+ <span>{link().label}</span>
+ <ArrowSquareOut class="size-3.5" />
+ </Button>
+ )}
+ </Show>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index 36bccabdb1..b4e74c4789 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -25,6 +25,10 @@ export {
ElicitationForm,
type ElicitationFormProps,
} from './ElicitationForm';
+export {
+ FailureNoticeCard,
+ type FailureNoticeCardProps,
+} from './FailureNoticeCard';
export { FoldedAnsiText } from './FoldedAnsiText';
export { FoldedOutput } from './FoldedOutput';
export { FoldedPathList } from './FoldedPathList';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
index dc7467f067..67d083ca13 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
@@ -325,6 +325,38 @@ describe('deriveMagicChipPresentation', () => {
});
});
+ it("shows a classified failure in the runtime's words for the person", () => {
+ const presentation = deriveMagicChipPresentation({
+ persistedStatus: 'acp_ready',
+ response: response({
+ parts: [],
+ stop: {
+ kind: 'failed',
+ message: 'Cursor usage limit reached. Raise the limit.',
+ notice: {
+ kind: 'provider_usage_limit',
+ title: 'Cursor usage limit reached',
+ body: 'Raise the spending limit in your Cursor dashboard, then send it again.',
+ link: {
+ label: 'Manage Cursor usage',
+ url: 'https://www.cursor.com/dashboard?tab=settings',
+ },
+ },
+ },
+ }),
+ });
+
+ expect(presentation).toEqual({
+ kind: 'working',
+ activity: {
+ label: 'Cursor usage limit reached',
+ detail:
+ 'Raise the spending limit in your Cursor dashboard, then send it again.',
+ busy: false,
+ },
+ });
+ });
+
it("shows the runtime's reason under a failed turn", () => {
const presentation = deriveMagicChipPresentation({
persistedStatus: 'acp_ready',
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
index ff303275ec..62c8ffa339 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
@@ -6,7 +6,7 @@ import type {
PendingInteraction,
ToolName,
} from '@service-agent-fold/generated/types';
-import { match } from 'ts-pattern';
+import { match, P } from 'ts-pattern';
/** The tool's own name, without its MCP server namespace. */
function toolLabel(name: ToolName): string {
@@ -275,6 +275,14 @@ function turnEndedActivity(
busy: false,
}))
.with({ kind: 'other' }, ({ reason }) => ({ label: reason, busy: false }))
+ // A failure the runtime wrote in the person's terms — a spent Cursor
+ // budget — is shown in those terms; the link lives in the session,
+ // which the chip opens.
+ .with({ kind: 'failed', notice: P.nonNullable }, ({ notice }) => ({
+ label: notice.title,
+ detail: notice.body,
+ busy: false,
+ }))
// The runtime errored the prompt. The label says that much; the
// runtime's own message goes in the detail line, because some of these
// are the user's to act on — a repository Cursor cannot reach, say.
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index 7dacc5deb1..182cb264a0 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -413,6 +413,43 @@ export type ElicitationSchema = {
required: string[];
};
+/** An external page where the person can act on a [`FailureNotice`]. */
+export type FailureLink = {
+ /** The link's text, e.g. `Manage Cursor usage`. */
+ label: string;
+ /** The page, absolute. */
+ url: string;
+};
+
+/**
+ * A turn failure the person who prompted can act on, in their terms.
+ *
+ * A runtime attaches this to the `session/prompt` error as its `data`; the
+ * fold reads it back onto the failed turn's stop reason. It exists so a
+ * billing wall or a disconnected integration renders as an instruction with
+ * somewhere to go, not as the runtime's error text - and so the runtime's
+ * error text, which for a report includes source locations, never has to
+ * double as the thing a person reads.
+ */
+export type FailureNotice = {
+ /** Which class of failure, for readers that treat one specially. */
+ kind: FailureNoticeKind;
+ /** One short line naming what happened. */
+ title: string;
+ /** What it means and what to do, in plain language. */
+ body: string;
+ /** Where acting on it happens, when that is somewhere else. */
+ link?: FailureLink | null;
+};
+
+/** The classes of actionable failure a runtime can report. */
+export type FailureNoticeKind =
+ /**
+ * The person's own account with the provider has no budget left for
+ * this work; the fix is on the provider's billing page.
+ */
+ 'provider_usage_limit';
+
/** A file modification a tool reported. */
export type FileDiff = {
/** The file that changed. */
@@ -870,6 +907,12 @@ export type StopReason =
kind: 'failed';
/** The runtime's error message, verbatim. */
message: string;
+ /**
+ * The failure in the person's terms, when the runtime classified it
+ * as one they can act on. Absent for an opaque failure, which a
+ * reader shows as `message` alone.
+ */
+ notice?: FailureNotice | null;
};
/**
diff --git a/crates/agent_fold/src/bin/fold_jsonl.rs b/crates/agent_fold/src/bin/fold_jsonl.rs
index 91184be277..b6dbc3f58a 100644
--- a/crates/agent_fold/src/bin/fold_jsonl.rs
+++ b/crates/agent_fold/src/bin/fold_jsonl.rs
@@ -621,7 +621,7 @@ fn render_stop(stop: &StopReason) -> String {
StopReason::Refusal => "refused".to_owned(),
StopReason::Cancelled => "cancelled".to_owned(),
StopReason::Other { reason } => format!("stopped: {reason}"),
- StopReason::Failed { message } => format!("failed: {message}"),
+ StopReason::Failed { message, .. } => format!("failed: {message}"),
}
}
diff --git a/crates/agent_fold/src/domain/fold/state.rs b/crates/agent_fold/src/domain/fold/state.rs
index fc08d2a565..987125aab2 100644
--- a/crates/agent_fold/src/domain/fold/state.rs
+++ b/crates/agent_fold/src/domain/fold/state.rs
@@ -305,7 +305,10 @@ impl FoldState {
TurnOutcome::Finished => crate::domain::model::StopReason::EndTurn,
TurnOutcome::Cancelled => crate::domain::model::StopReason::Cancelled,
TurnOutcome::Failed { message } => {
- crate::domain::model::StopReason::Failed { message }
+ crate::domain::model::StopReason::Failed {
+ message,
+ notice: None,
+ }
}
});
StepChange::message(stop.and_then(|stop| self.close_turn(Some(stop))))
@@ -367,7 +370,7 @@ impl FoldState {
if self.pending_config_requests.remove(id) || control.is_some() {
StepChange::message(control)
} else {
- StepChange::message(self.fail_turn(id, &error.message))
+ StepChange::message(self.fail_turn(id, error))
}
}
RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => Vec::new(),
diff --git a/crates/agent_fold/src/domain/fold/turn.rs b/crates/agent_fold/src/domain/fold/turn.rs
index 128a2c7055..7eae970e69 100644
--- a/crates/agent_fold/src/domain/fold/turn.rs
+++ b/crates/agent_fold/src/domain/fold/turn.rs
@@ -1,9 +1,9 @@
//! Opening, closing, and failing turns.
use crate::domain::error::FoldError;
-use crate::domain::model::{Author, FoldedMessage, MessagePart, StopReason, TurnId};
+use crate::domain::model::{Author, FailureNotice, FoldedMessage, MessagePart, StopReason, TurnId};
use agent_client_protocol::RawJsonRpcParams;
-use agent_client_protocol::schema::v1::{PromptRequest, RequestId};
+use agent_client_protocol::schema::v1::{Error, PromptRequest, RequestId};
use agent_runtime_protocol::domain::action::AgentActionId;
use macro_user_id::user_id::MacroUserIdStr;
use non_empty::NonEmpty;
@@ -186,7 +186,7 @@ impl FoldState {
/// an agent message that exists: here the agent message is created if
/// need be, so the failure has somewhere to live and the turn is
/// unambiguously over.
- pub(super) fn fail_turn(&mut self, response_id: &RequestId, message: &str) -> Option<Changed> {
+ pub(super) fn fail_turn(&mut self, response_id: &RequestId, error: &Error) -> Option<Changed> {
let closes_the_open_turn = self
.turn
.as_ref()
@@ -204,7 +204,8 @@ impl FoldState {
None => self.mint_agent_message(turn.id),
};
self.messages[agent].stop = Some(StopReason::Failed {
- message: message.to_owned(),
+ message: error.message.clone(),
+ notice: FailureNotice::from_error_data(error.data.as_ref()),
});
Some(changed)
}
diff --git a/crates/agent_fold/src/domain/model.rs b/crates/agent_fold/src/domain/model.rs
index 20d462e941..d0ac208829 100644
--- a/crates/agent_fold/src/domain/model.rs
+++ b/crates/agent_fold/src/domain/model.rs
@@ -43,6 +43,7 @@ mod tool;
/// Macro user tools.
mod user_tool;
+pub use agent_runtime_protocol::domain::turn::{FailureLink, FailureNotice, FailureNoticeKind};
pub use elicitation::{
AnsweredChoice, AnsweredField, AnsweredValue, ElicitationOption, ElicitationOutcome,
ElicitationProperty, ElicitationPropertySchema, ElicitationRequest, ElicitationRequestId,
diff --git a/crates/agent_fold/src/domain/model/part.rs b/crates/agent_fold/src/domain/model/part.rs
index 05223f651e..6ddd369022 100644
--- a/crates/agent_fold/src/domain/model/part.rs
+++ b/crates/agent_fold/src/domain/model/part.rs
@@ -13,6 +13,7 @@ use super::permission::{PermissionOption, PermissionOutcome};
use super::plan::PlanEntry;
use super::tool::{ToolDetail, ToolName, ToolStatus};
use super::user_tool::UserToolOutcome;
+use agent_runtime_protocol::domain::turn::FailureNotice;
/// A unit of renderable content.
#[derive(Debug, Clone, PartialEq, Serialize, Type)]
@@ -218,6 +219,11 @@ pub enum StopReason {
Failed {
/// The runtime's error message, verbatim.
message: String,
+ /// The failure in the person's terms, when the runtime classified it
+ /// as one they can act on. Absent for an opaque failure, which a
+ /// reader shows as `message` alone.
+ #[serde(default)]
+ notice: Option<FailureNotice>,
},
}
diff --git a/crates/agent_fold/src/domain/model/search.rs b/crates/agent_fold/src/domain/model/search.rs
index 642e60aca4..6a1fbe3776 100644
--- a/crates/agent_fold/src/domain/model/search.rs
+++ b/crates/agent_fold/src/domain/model/search.rs
@@ -29,7 +29,7 @@ impl FoldedMessage {
for part in self.parts.iter() {
text.part(part);
}
- if let Some(StopReason::Failed { message }) = &self.stop {
+ if let Some(StopReason::Failed { message, .. }) = &self.stop {
text.push(message);
}
text.finish()
diff --git a/crates/agent_fold/src/domain/model/search/test.rs b/crates/agent_fold/src/domain/model/search/test.rs
index c73d39f6fc..a71008694b 100644
--- a/crates/agent_fold/src/domain/model/search/test.rs
+++ b/crates/agent_fold/src/domain/model/search/test.rs
@@ -99,6 +99,7 @@ fn searchable_text_includes_folded_json_and_visible_failure() {
}]);
message.stop = Some(StopReason::Failed {
message: "runtime disconnected".to_owned(),
+ notice: None,
});
assert_eq!(
diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rs
index c09e6ffdbc..8f4964eeb7 100644
--- a/crates/agent_fold/src/domain/test/fold.rs
+++ b/crates/agent_fold/src/domain/test/fold.rs
@@ -2,8 +2,9 @@ use super::util::{CapturedFields, TURN, capturing_warnings, parse_log};
use crate::domain::fold::fold;
use crate::domain::log::{AgentSessionLog, Message};
use crate::domain::model::{
- AgentRequestId, Author, Control, ControlOutcome, FoldedMessage, MessagePart, PermissionOutcome,
- StopReason, ToolDetail, ToolName, ToolStatus, ToolUseId, TurnId,
+ AgentRequestId, Author, Control, ControlOutcome, FailureLink, FailureNotice, FailureNoticeKind,
+ FoldedMessage, MessagePart, PermissionOutcome, StopReason, ToolDetail, ToolName, ToolStatus,
+ ToolUseId, TurnId,
};
use agent_client_protocol::RawJsonRpcMessage;
use agent_runtime_protocol::domain::schema::v0::ToServerMessage;
@@ -678,12 +679,73 @@ fn a_prompt_answered_with_an_error_ends_its_turn() {
Some(StopReason::Failed {
message: "Internal error: Bad Request: bad request: Authorization header is badly \
formatted"
- .to_owned()
+ .to_owned(),
+ notice: None,
}),
"the runtime's own words, carried verbatim"
);
}
+/// A runtime that classified the failure as the person's to act on says so
+/// in the error's `data`, and the fold carries that through as the notice a
+/// reader shows instead of the runtime's message.
+#[test]
+fn a_prompt_error_carrying_a_notice_fails_its_turn_with_the_notice() {
+ let (prompt, _) = FAILED_PROMPT
+ .split_once('\n')
+ .expect("the fixture has two frames");
+ let error = concat!(
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","error":{"code":-32603,"#,
+ r#""message":"Cursor has no budget left.","#,
+ r#""data":{"kind":"provider_usage_limit","title":"Cursor usage limit reached","#,
+ r#""body":"Raise the limit, then send your message again.","#,
+ r#""link":{"label":"Manage Cursor usage","url":"https://www.cursor.com/dashboard?tab=settings"}}}}}"#,
+ );
+
+ let messages = fold(parse_log(&format!("{prompt}\n{error}")));
+
+ let agent = messages.last().expect("an agent message");
+ assert_eq!(
+ agent.stop,
+ Some(StopReason::Failed {
+ message: "Cursor has no budget left.".to_owned(),
+ notice: Some(FailureNotice {
+ kind: FailureNoticeKind::ProviderUsageLimit,
+ title: "Cursor usage limit reached".to_owned(),
+ body: "Raise the limit, then send your message again.".to_owned(),
+ link: Some(FailureLink {
+ label: "Manage Cursor usage".to_owned(),
+ url: "https://www.cursor.com/dashboard?tab=settings".to_owned(),
+ }),
+ }),
+ })
+ );
+}
+
+/// Error `data` that is not a notice - another runtime's debugging payload -
+/// leaves the failure opaque rather than half-parsed.
+#[test]
+fn a_prompt_error_with_unrelated_data_fails_its_turn_without_a_notice() {
+ let (prompt, _) = FAILED_PROMPT
+ .split_once('\n')
+ .expect("the fixture has two frames");
+ let error = concat!(
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","error":{"code":-32603,"#,
+ r#""message":"boom","data":{"details":"stack trace here"}}}}"#,
+ );
+
+ let messages = fold(parse_log(&format!("{prompt}\n{error}")));
+
+ let agent = messages.last().expect("an agent message");
+ assert_eq!(
+ agent.stop,
+ Some(StopReason::Failed {
+ message: "boom".to_owned(),
+ notice: None,
+ })
+ );
+}
+
/// The failure lands on whatever the agent had already said, rather than
/// opening a second message beside it.
#[test]
diff --git a/crates/agent_fold/src/domain/test/replay.rs b/crates/agent_fold/src/domain/test/replay.rs
index 457105fec1..ae99470d87 100644
--- a/crates/agent_fold/src/domain/test/replay.rs
+++ b/crates/agent_fold/src/domain/test/replay.rs
@@ -462,6 +462,7 @@ fn generic_terminal_facts_restore_stops_without_changing_load_success_semantics(
json!({"kind":"failed","message":"provider failed"}),
StopReason::Failed {
message: "provider failed".into(),
+ notice: None,
},
),
] {
diff --git a/crates/agent_runtime_protocol/src/domain/turn.rs b/crates/agent_runtime_protocol/src/domain/turn.rs
index 282ad9221a..3e877677fa 100644
--- a/crates/agent_runtime_protocol/src/domain/turn.rs
+++ b/crates/agent_runtime_protocol/src/domain/turn.rs
@@ -3,6 +3,59 @@ use agent_client_protocol::JsonRpcNotification;
use agent_client_protocol::schema::v1::SessionId;
use serde::{Deserialize, Serialize};
+/// A turn failure the person who prompted can act on, in their terms.
+///
+/// A runtime attaches this to the `session/prompt` error as its `data`; the
+/// fold reads it back onto the failed turn's stop reason. It exists so a
+/// billing wall or a disconnected integration renders as an instruction with
+/// somewhere to go, not as the runtime's error text - and so the runtime's
+/// error text, which for a report includes source locations, never has to
+/// double as the thing a person reads.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
+#[serde(rename_all = "camelCase")]
+pub struct FailureNotice {
+ /// Which class of failure, for readers that treat one specially.
+ pub kind: FailureNoticeKind,
+ /// One short line naming what happened.
+ pub title: String,
+ /// What it means and what to do, in plain language.
+ pub body: String,
+ /// Where acting on it happens, when that is somewhere else.
+ #[serde(default)]
+ pub link: Option<FailureLink>,
+}
+
+impl FailureNotice {
+ /// The notice a prompt error's `data` carries, if it carries one.
+ ///
+ /// Anything else in `data` - another runtime's debugging payload, a bare
+ /// string - is not a notice and reads as `None`, so an unclassified
+ /// failure is never dressed up as an actionable one.
+ #[must_use]
+ pub fn from_error_data(data: Option<&serde_json::Value>) -> Option<Self> {
+ data.and_then(|data| serde_json::from_value(data.clone()).ok())
+ }
+}
+
+/// The classes of actionable failure a runtime can report.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
+#[serde(rename_all = "snake_case")]
+pub enum FailureNoticeKind {
+ /// The person's own account with the provider has no budget left for
+ /// this work; the fix is on the provider's billing page.
+ ProviderUsageLimit,
+}
+
+/// An external page where the person can act on a [`FailureNotice`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
+#[serde(rename_all = "camelCase")]
+pub struct FailureLink {
+ /// The link's text, e.g. `Manage Cursor usage`.
+ pub label: String,
+ /// The page, absolute.
+ pub url: String,
+}
+
/// Completes the currently projected turn without inventing a prompt response.
/// This optional extension conveys history facts; it does not certify a load,
/// change load success semantics, or imply completion when absent.
diff --git a/crates/cursor_cloud_agents/src/api.rs b/crates/cursor_cloud_agents/src/api.rs
index f50db8ff70..f5b72e43d0 100644
--- a/crates/cursor_cloud_agents/src/api.rs
+++ b/crates/cursor_cloud_agents/src/api.rs
@@ -260,6 +260,22 @@ fn classify_repository_rejection(
None
}
+/// Whether a 4xx body is Cursor refusing for want of budget.
+///
+/// Keyed on the envelope's `error.code` alone. The message names a dollar
+/// figure and a dashboard, both Cursor's to reword; the code is the contract.
+/// Reached for a create and for a follow-up run alike - a budget runs out
+/// mid-conversation as readily as before it.
+fn classify_usage_limit(body: &str) -> Option<crate::domain::error::UsageLimitExceeded> {
+ let envelope = serde_json::from_str::<crate::api::wire::ApiErrorEnvelope>(body).ok()?;
+ crate::domain::error::UsageLimitExceeded::CODES
+ .contains(&envelope.error.code.as_str())
+ .then(|| crate::domain::error::UsageLimitExceeded {
+ code: envelope.error.code,
+ detail: body.to_owned(),
+ })
+}
+
/// The Cursor cloud API client.
#[derive(Debug, Clone)]
pub struct CursorClient {
@@ -417,6 +433,9 @@ impl CursorClient {
{
if !status.is_success() {
if status.is_client_error() && status != reqwest::StatusCode::REQUEST_TIMEOUT {
+ if let Some(exceeded) = classify_usage_limit(text) {
+ return Err(rootcause::report!(exceeded).into_dynamic());
+ }
return Err(
rootcause::report!(crate::domain::error::PromptRejected(format!(
"cursor POST {path} -> {status}: {text}"
diff --git a/crates/cursor_cloud_agents/src/api/test.rs b/crates/cursor_cloud_agents/src/api/test.rs
index 1c63f13a17..7428511542 100644
--- a/crates/cursor_cloud_agents/src/api/test.rs
+++ b/crates/cursor_cloud_agents/src/api/test.rs
@@ -437,6 +437,80 @@ async fn an_unrelated_client_error_is_still_a_plain_rejection() {
);
}
+/// The body Cursor answered with in production when the account behind the
+/// key had spent its background-agent budget.
+const USAGE_LIMIT_BODY: &str = r#"{"error":{"code":"usage_limit_exceeded","message":"You need to increase your hard limit. Background Agent requires at least $2 remaining until your hard limit. Manage it at https://www.cursor.com/dashboard?tab=settings."}}"#;
+
+/// An exhausted Cursor budget is the person's to fix, so it arrives typed -
+/// keyed on the code, with Cursor's body kept for the logs and a notice that
+/// says where to go.
+#[tokio::test]
+async fn an_exhausted_usage_limit_is_typed_with_a_notice() {
+ let base_url = stand_in_server("400 Bad Request", USAGE_LIMIT_BODY);
+ let error = client_against(base_url)
+ .create_agent("prompt", Some(&repo()), true, &[], None)
+ .await
+ .expect_err("the stand-in rejects every create");
+ let exceeded = error
+ .downcast_current_context::<crate::domain::error::UsageLimitExceeded>()
+ .expect("a usage limit is typed as one");
+ assert_eq!(exceeded.code, "usage_limit_exceeded");
+ assert_eq!(exceeded.detail, USAGE_LIMIT_BODY);
+ let notice = exceeded.notice();
+ assert_eq!(
+ notice.kind,
+ crate::domain::error::FailureNoticeKind::ProviderUsageLimit
+ );
+ assert_eq!(
+ notice.link.as_ref().map(|link| link.url.as_str()),
+ Some("https://www.cursor.com/dashboard?tab=settings")
+ );
+ let refusal = exceeded.refusal();
+ assert!(
+ !refusal.message.contains("usage_limit_exceeded") && !refusal.message.contains("$2"),
+ "cursor's own wording stays in the logs: {}",
+ refusal.message
+ );
+}
+
+/// A follow-up run on an existing agent hits the same wall when the budget
+/// runs out mid-conversation, and is classified the same way.
+#[tokio::test]
+async fn an_exhausted_usage_limit_on_a_follow_up_run_is_typed_too() {
+ let base_url = stand_in_server("400 Bad Request", USAGE_LIMIT_BODY);
+ let error = client_against(base_url)
+ .create_run(&agent(), "prompt", None)
+ .await
+ .expect_err("the stand-in rejects every run");
+ assert!(
+ error
+ .downcast_current_context::<crate::domain::error::UsageLimitExceeded>()
+ .is_some(),
+ "got {error:?}"
+ );
+}
+
+/// The message is the same wall in different words at another time; only the
+/// code is stable. A body with a different code and the same words is not a
+/// usage limit.
+#[tokio::test]
+async fn a_usage_limit_is_matched_on_the_code_not_the_message() {
+ let base_url = stand_in_server(
+ "400 Bad Request",
+ r#"{"error":{"code":"validation_error","message":"You need to increase your hard limit."}}"#,
+ );
+ let error = client_against(base_url)
+ .create_agent("prompt", Some(&repo()), true, &[], None)
+ .await
+ .expect_err("the stand-in rejects every create");
+ assert!(
+ error
+ .downcast_current_context::<crate::domain::error::UsageLimitExceeded>()
+ .is_none(),
+ "the wording alone does not classify"
+ );
+}
+
fn agent() -> CursorAgentId {
CursorAgentId::new("bc-00000000-0000-0000-0000-000000000001".to_owned())
}
diff --git a/crates/cursor_cloud_agents/src/domain/error.rs b/crates/cursor_cloud_agents/src/domain/error.rs
index ddd93aa0b5..934261560b 100644
--- a/crates/cursor_cloud_agents/src/domain/error.rs
+++ b/crates/cursor_cloud_agents/src/domain/error.rs
@@ -2,6 +2,7 @@
use crate::domain::model::RepoUrl;
use agent_client_protocol::schema::v1::SessionId;
+pub use agent_runtime_protocol::domain::turn::{FailureLink, FailureNotice, FailureNoticeKind};
use thiserror::Error;
/// Why a session operation failed.
@@ -22,11 +23,11 @@ pub enum SessionError {
#[error("{0}")]
Cursor(rootcause::Report),
/// The provider refused the prompt for a reason the person who sent it
- /// can act on. Carries the message meant for them and nothing else: it is
+ /// can act on. Carries what is meant for them and nothing else: it is
/// what the `session/prompt` error says, so a report's decorations (a
/// bullet, a source location) would be read as part of the instruction.
#[error("{0}")]
- Rejected(String),
+ Rejected(PromptRefusal),
}
impl From<rootcause::Report> for SessionError {
@@ -35,6 +36,92 @@ impl From<rootcause::Report> for SessionError {
}
}
+/// What a refused prompt tells the person who sent it.
+///
+/// `message` is the `session/prompt` error's message and is always present.
+/// `notice` is the same refusal in the shape a reader renders as an
+/// instruction with somewhere to go; it exists only for the refusals a
+/// person can resolve outside Macro, and travels as the error's `data`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PromptRefusal {
+ /// One plain sentence or two, no report decorations.
+ pub message: String,
+ /// The refusal as a rendered notice, when there is more to say than a line.
+ pub notice: Option<FailureNotice>,
+}
+
+impl PromptRefusal {
+ /// A refusal that is only its message.
+ #[must_use]
+ pub fn plain(message: impl Into<String>) -> Self {
+ Self {
+ message: message.into(),
+ notice: None,
+ }
+ }
+}
+
+impl std::fmt::Display for PromptRefusal {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(&self.message)
+ }
+}
+
+/// A prompt Cursor refused because the account behind the API key has no
+/// background-agent budget left.
+///
+/// Seen in production as a 400 with code `usage_limit_exceeded`: "You need
+/// to increase your hard limit. Background Agent requires at least $2
+/// remaining until your hard limit." A fact about the person's own Cursor
+/// account, fixed on Cursor's dashboard, so it is the person's to read - not
+/// an internal error, which is how the raw report presented it.
+#[derive(Debug, Error)]
+#[error("cursor refused the prompt ({code}): {detail}")]
+pub struct UsageLimitExceeded {
+ /// Cursor's error code, one of [`Self::CODES`].
+ pub code: String,
+ /// Cursor's own error body, verbatim, for the logs.
+ pub detail: String,
+}
+
+impl UsageLimitExceeded {
+ /// Cursor's error codes for an exhausted budget.
+ ///
+ /// Matched on the structured `error.code`, never the message: Cursor's
+ /// wording (and the dollar figure in it) is theirs to change.
+ pub const CODES: [&'static str; 1] = ["usage_limit_exceeded"];
+
+ /// Where the limit is raised.
+ pub const DASHBOARD_URL: &'static str = "https://www.cursor.com/dashboard?tab=settings";
+
+ /// What to show the person who sent the prompt.
+ #[must_use]
+ pub fn notice(&self) -> FailureNotice {
+ FailureNotice {
+ kind: FailureNoticeKind::ProviderUsageLimit,
+ title: "Cursor usage limit reached".to_owned(),
+ body: "Your Cursor account has no background-agent budget left, so this message \
+ wasn't sent. Raise the spending limit in your Cursor dashboard, then send \
+ it again."
+ .to_owned(),
+ link: Some(FailureLink {
+ label: "Manage Cursor usage".to_owned(),
+ url: Self::DASHBOARD_URL.to_owned(),
+ }),
+ }
+ }
+
+ /// The refusal as the `session/prompt` error carries it.
+ #[must_use]
+ pub fn refusal(&self) -> PromptRefusal {
+ let notice = self.notice();
+ PromptRefusal {
+ message: format!("{} {}", notice.title, notice.body),
+ notice: Some(notice),
+ }
+ }
+}
+
/// A provider response proving a prompt was rejected before execution.
#[derive(Debug, Error)]
#[error("{0}")]
diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rs
index f752a4a397..cd66040cd6 100644
--- a/crates/cursor_cloud_agents/src/domain/service.rs
+++ b/crates/cursor_cloud_agents/src/domain/service.rs
@@ -39,7 +39,7 @@
mod test;
use crate::domain::artifact::{ArtifactListing, CollectedArtifact, inline_text, mime_type};
-use crate::domain::error::SessionError;
+use crate::domain::error::{PromptRefusal, SessionError};
use crate::domain::event::CursorEvent;
use crate::domain::journal::{CursorJournal, JournalEntry, JournalInput, ReplayMachine};
use crate::domain::model::{
@@ -259,30 +259,41 @@ fn captured_content(
.collect()
}
-/// Restate a repository rejection as something the person who prompted can
-/// act on, leaving every other failure exactly as it arrived.
+/// Restate a rejection the person who prompted can act on - a repository
+/// Cursor cannot reach, a Cursor account out of budget - in their terms,
+/// leaving every other failure exactly as it arrived.
///
/// The result is a [`SessionError::Rejected`], so it takes the same path a
/// [`PromptRejected`](crate::domain::error::PromptRejected) already takes:
-/// the prompt is journalled as aborted and the message travels to the client
+/// the prompt is journalled as aborted and the refusal travels to the client
/// as the `session/prompt` error. Cursor's own body stays in the tracing event —
/// it names codes and ids that mean nothing to a reader of the chip.
-fn explain_repository_rejection(error: SessionError) -> SessionError {
+fn explain_rejection(error: SessionError) -> SessionError {
let SessionError::Cursor(report) = &error else {
return error;
};
- let Some(unavailable) =
+ if let Some(unavailable) =
report.downcast_current_context::<crate::domain::error::RepositoryUnavailable>()
- else {
- return error;
- };
- tracing::warn!(
- repo = %unavailable.repo,
- reason = %unavailable.reason,
- detail = %unavailable.detail,
- "cursor rejected the prompt: it could not use the session's repository"
- );
- SessionError::Rejected(unavailable.user_message())
+ {
+ tracing::warn!(
+ repo = %unavailable.repo,
+ reason = %unavailable.reason,
+ detail = %unavailable.detail,
+ "cursor rejected the prompt: it could not use the session's repository"
+ );
+ return SessionError::Rejected(PromptRefusal::plain(unavailable.user_message()));
+ }
+ if let Some(exceeded) =
+ report.downcast_current_context::<crate::domain::error::UsageLimitExceeded>()
+ {
+ tracing::warn!(
+ code = %exceeded.code,
+ detail = %exceeded.detail,
+ "cursor rejected the prompt: the account's usage limit is exhausted"
+ );
+ return SessionError::Rejected(exceeded.refusal());
+ }
+ error
}
/// Whether a failed create is a definite refusal — the prompt never ran, so
@@ -925,15 +936,14 @@ where
// request there, which no later correction undoes.
Err(error) => {
tracing::warn!(error = ?error, "could not choose a repository for this session");
- Err(SessionError::Rejected(
- "Couldn't prepare repository access for this session. Please retry; if this persists, check your GitHub connection."
- .to_owned(),
- ))
+ Err(SessionError::Rejected(PromptRefusal::plain(
+ "Couldn't prepare repository access for this session. Please retry; if this persists, check your GitHub connection.",
+ )))
}
}
}
};
- let (agent, run) = match created.map_err(explain_repository_rejection) {
+ let (agent, run) = match created.map_err(explain_rejection) {
Ok(created) => created,
Err(error) => {
if is_prompt_rejection(&error) {
@@ -953,7 +963,7 @@ where
// the agent can see.
if creating_agent {
let reason = match &error {
- SessionError::Rejected(message) => Some(message.clone()),
+ SessionError::Rejected(refusal) => Some(refusal.message.clone()),
_ => None,
};
session
@@ -1029,7 +1039,7 @@ where
// up on a run still going, not a prompt refused before it ran.
let interrupted = match &outcome {
Err(SessionError::Cursor(error)) => Some(error.to_string()),
- Err(SessionError::Rejected(message)) => Some(message.clone()),
+ Err(SessionError::Rejected(refusal)) => Some(refusal.message.clone()),
_ => None,
};
if let Some(interrupted) = interrupted {
@@ -1691,13 +1701,12 @@ where
attempts = POLL_ATTEMPTS,
"gave up waiting; Cursor still reports a non-terminal status"
);
- return Err(SessionError::Rejected(
+ return Err(SessionError::Rejected(PromptRefusal::plain(
"Cursor has been working on this for over two hours and Macro stopped \
waiting. Send another message to continue: if Cursor has finished by \
then, that message picks up what it did, and if not, the run is \
- cancelled and the conversation starts fresh from there."
- .into(),
- ));
+ cancelled and the conversation starts fresh from there.",
+ )));
};
if strict
&& !session
diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rs
index 1a9cb4551b..5d9d8df0ea 100644
--- a/crates/cursor_cloud_agents/src/domain/service/test.rs
+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::domain::error::SessionError;
+use crate::domain::error::{PromptRefusal, SessionError};
use crate::domain::event::{CursorEvent, InteractionUpdate, ToolCallEvent, Truncation};
use crate::domain::journal::NativeRecord;
use crate::domain::model::{
@@ -2577,6 +2577,7 @@ async fn actual_load_frames_restore_terminal_outcomes_and_leave_partial_tail_ope
Some(RunStatus::Error),
Some(FoldStop::Failed {
message: "Agent run ended in Error".into(),
+ notice: None,
}),
),
(None, None),
@@ -2692,6 +2693,58 @@ async fn an_unconnected_repository_reaches_the_client_as_an_instruction() {
);
}
+/// A Cursor account out of budget is the person's to fix on Cursor's
+/// dashboard, so it reaches the client as a refusal with a notice - title,
+/// plain body, the dashboard link - and never as the report, whose source
+/// locations and span dump are for the logs.
+#[tokio::test]
+async fn an_exhausted_cursor_budget_reaches_the_client_as_a_notice() {
+ let repo = RepoUrl::parse("https://github.com/macro-inc/macro").expect("an https remote");
+ let (service, cursor, _output) = service(Some(repo));
+ let id = service.new_session(Path::new(""), vec![]);
+ cursor.script_usage_limit_rejection();
+
+ let error = service
+ .prompt(&id, "do the thing")
+ .await
+ .expect_err("an exhausted budget fails the prompt");
+
+ let SessionError::Rejected(refusal) = &error else {
+ panic!("a spent budget is a refusal, not a Cursor failure: {error:?}");
+ };
+ let notice = refusal
+ .notice
+ .as_ref()
+ .expect("a spent budget carries a notice");
+ assert_eq!(notice.title, "Cursor usage limit reached");
+ assert_eq!(
+ notice.link.as_ref().map(|link| link.url.as_str()),
+ Some("https://www.cursor.com/dashboard?tab=settings")
+ );
+ for text in [&refusal.message, &notice.body] {
+ assert!(
+ !text.contains("usage_limit_exceeded") && !text.contains("$2"),
+ "cursor's own body stays in the logs: {text}"
+ );
+ assert!(
+ !text.contains(".rs:") && !text.contains("├"),
+ "no report decoration reaches the person: {text}"
+ );
+ }
+ assert!(
+ service
+ .session(&id)
+ .expect("session exists")
+ .state
+ .lock()
+ .expect("state poisoned")
+ .journal_entries
+ .iter()
+ .any(|entry| matches!(entry.input, JournalInput::PromptAborted(_))),
+ "a refused prompt is journalled as aborted"
+ );
+}
+
/// After Cursor refuses the first create, the next prompt is almost always
/// about the refusal ("what's the error?"), which is no evidence of where
/// the work belongs. The repository decided from the first prompt has to
@@ -2971,7 +3024,7 @@ async fn a_run_that_never_ends_is_reported_in_words_the_prompter_can_act_on() {
.prompt(&session, "do the thing")
.await
.expect_err("the turn cannot close on a run that never ends");
- let SessionError::Rejected(message) = &error else {
+ let SessionError::Rejected(PromptRefusal { message, .. }) = &error else {
panic!("a run still going is not a Cursor failure: {error:?}");
};
// The decorations a report carries would be read as part of the sentence.
diff --git a/crates/cursor_cloud_agents/src/inbound/acp.rs b/crates/cursor_cloud_agents/src/inbound/acp.rs
index 1ab1ea002c..ada91452fb 100644
--- a/crates/cursor_cloud_agents/src/inbound/acp.rs
+++ b/crates/cursor_cloud_agents/src/inbound/acp.rs
@@ -28,6 +28,7 @@
#[cfg(test)]
mod test;
+use crate::domain::error::SessionError;
use crate::domain::model::{McpHeader, McpServer, McpTransport};
use crate::domain::model_options::{MODEL_CONFIG_ID, cursor_model_config_options};
use crate::domain::ports::{
@@ -451,8 +452,7 @@ where
}
Err(error) => {
tracing::error!(error = %error, "prompt failed");
- let _ = responder
- .respond_with_error(AcpError::new(-32603, error.to_string()));
+ let _ = responder.respond_with_error(prompt_error(&error));
}
}
Ok(())
@@ -640,6 +640,24 @@ async fn advertise_slash_commands(notifier: &AcpNotifier, session: &SessionId) {
}
}
+/// The `session/prompt` error for a failed turn.
+///
+/// The message is the error's `Display` - one sentence for a refusal, the
+/// report for anything else. A refusal the person can act on also carries
+/// its notice as the error's `data`, which is where the fold picks it up.
+fn prompt_error(error: &SessionError) -> AcpError {
+ let acp_error = AcpError::new(-32603, error.to_string());
+ match error {
+ SessionError::Rejected(refusal) => acp_error.data(
+ refusal
+ .notice
+ .as_ref()
+ .and_then(|notice| serde_json::to_value(notice).ok()),
+ ),
+ _ => acp_error,
+ }
+}
+
/// Concatenate a prompt's content blocks into the single string Cursor takes.
fn prompt_text(blocks: &[ContentBlock]) -> String {
blocks
diff --git a/crates/cursor_cloud_agents/src/inbound/acp/test.rs b/crates/cursor_cloud_agents/src/inbound/acp/test.rs
index e4b1c34cd5..9f0f51509c 100644
--- a/crates/cursor_cloud_agents/src/inbound/acp/test.rs
+++ b/crates/cursor_cloud_agents/src/inbound/acp/test.rs
@@ -1067,6 +1067,53 @@ async fn setting_an_unoffered_model_is_refused() {
);
}
+/// A refusal the person can act on answers the prompt with its notice in the
+/// error's `data` - where the fold reads it - and a one-sentence message,
+/// never the report with its source locations.
+#[tokio::test]
+async fn a_usage_limit_refusal_answers_the_prompt_with_a_notice() {
+ let cursor = FakeCursor::new();
+ cursor.script_usage_limit_rejection();
+ let (_service, mut client) = serve_over_channel(cursor, |_| {});
+
+ let session = expect_result(
+ &client
+ .call(
+ 1,
+ "session/new",
+ serde_json::json!({"cwd": "/workspace", "mcpServers": []}),
+ )
+ .await,
+ )["sessionId"]
+ .as_str()
+ .expect("a session id")
+ .to_owned();
+
+ let response = client
+ .call(
+ 2,
+ "session/prompt",
+ serde_json::json!({
+ "sessionId": session,
+ "prompt": [{ "type": "text", "text": "do it" }],
+ }),
+ )
+ .await;
+
+ let error = response.get("error").expect("a refused prompt is an error");
+ assert_eq!(error["data"]["kind"], "provider_usage_limit");
+ assert_eq!(error["data"]["title"], "Cursor usage limit reached");
+ assert_eq!(
+ error["data"]["link"]["url"],
+ "https://www.cursor.com/dashboard?tab=settings"
+ );
+ let message = error["message"].as_str().expect("a message");
+ assert!(
+ !message.contains("usage_limit_exceeded") && !message.contains(".rs:"),
+ "cursor's body and the report stay in the logs: {message}"
+ );
+}
+
/// A restored session's next run asks for the model it was using before the
/// restart, params re-resolved from the live model table.
///
diff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rs
index 230e0ada43..73d7380fbc 100644
--- a/crates/cursor_cloud_agents/src/testing.rs
+++ b/crates/cursor_cloud_agents/src/testing.rs
@@ -197,6 +197,7 @@ struct FakeCursorState {
model_gate: Option<tokio::sync::oneshot::Receiver<()>>,
reject_create: bool,
reject_create_for_repository: bool,
+ reject_create_for_usage_limit: bool,
/// Answers for `list_artifacts`, consumed in order; the last one sticks.
artifact_listings: Vec<Result<Vec<ArtifactListing>, String>>,
/// Bodies `fetch_artifact` answers with, by artifact path.
@@ -322,6 +323,12 @@ impl FakeCursor {
self.inner.lock().unwrap().reject_create_for_repository = true;
}
+ /// Reject the next create (agent or run) the way Cursor does when the
+ /// account's background-agent budget is spent.
+ pub fn script_usage_limit_rejection(&self) {
+ self.inner.lock().unwrap().reject_create_for_usage_limit = true;
+ }
+
/// Set the models `list_models` answers with.
pub fn script_models(&self, models: Vec<CursorModel>) {
self.inner.lock().expect("fake cursor poisoned").models = models;
@@ -449,6 +456,16 @@ impl FakeCursor {
}
}
+/// The refusal Cursor answered a production create with once the account's
+/// budget was spent, as [`crate::api`] types it.
+fn usage_limit_exceeded() -> rootcause::Report {
+ rootcause::report!(crate::domain::error::UsageLimitExceeded {
+ code: "usage_limit_exceeded".to_owned(),
+ detail: r#"{"error":{"code":"usage_limit_exceeded","message":"You need to increase your hard limit. Background Agent requires at least $2 remaining until your hard limit. Manage it at https://www.cursor.com/dashboard?tab=settings."}}"#.to_owned(),
+ })
+ .into_dynamic()
+}
+
impl CursorAgents for FakeCursor {
async fn create_agent(
&self,
@@ -486,6 +503,9 @@ impl CursorAgents for FakeCursor {
))
.into_dynamic());
}
+ if std::mem::take(&mut state.reject_create_for_usage_limit) {
+ return Err(usage_limit_exceeded());
+ }
state.next_run += 1;
Ok((
CursorAgentId::new("bc-fake"),
@@ -516,6 +536,9 @@ impl CursorAgents for FakeCursor {
))
.into_dynamic());
}
+ if std::mem::take(&mut state.reject_create_for_usage_limit) {
+ return Err(usage_limit_exceeded());
+ }
state.next_run += 1;
Ok(CursorRunId::new(format!("run-fake-{}", state.next_run)))
}