feat(cursor): detect inline model errors, surface, notify, and bridge (#878) (#987)

Cursor ACP sessions can fail mid-turn with a transient model error that the
agent reports inline rather than as an RPC rejection. HAPI treated those turns
as successful, so the session went quiet with no banner, no push, and no way to
resume without retyping the prompt.

This adds the full path:

- detect: classify inline/stderr model errors from the Cursor ACP stream,
  requiring strong signatures before typing a failure as a model error
- surface: persist `lastModelError` on session metadata; render a chat banner
  and a session-list indicator, with the prompt text kept out of list/SSE
  summaries so they never ship up to 32 KB of user prompt
- notify: deliver a push for an unacknowledged error, watermarked on the hub
  copy so a restart does not re-page the same eventId
- bridge & retry: offer a one-shot recovery prompt that replays the failed
  turn, bound to the originating eventId and gated so a real user turn always
  supersedes it. Auto-bridge is opt-in and defaults to OFF, persisted in hub
  settings and fanned out to live Cursor CLIs.

Re-cut onto current upstream/main. The branch had accumulated 108 iterative
hardening commits against a 289-commit-older base; replaying them individually
would have re-resolved the same conflicts ~100 times. The pre-re-cut tip was
2c28a1365 if the granular history is ever needed.

Absorbing upstream required adapting to three refactors that landed meanwhile:

- `MessageQueue2` grew an `internal?: boolean` control-message flag upstream
  while this branch added richer `internal` provenance. Unified on a tagged
  `QueueItemInternal` union (`control` | `model-error-bridge`) so one field
  carries one concept. `hasPendingNonBridgeTurn()` now treats *any* internal
  item as non-user: otherwise a queued `/auto-review` control slash would have
  counted as a user turn and wrongly superseded a live bridge.
- `AcpSdkBackend.prompt()` gained a `timing` callback upstream; merged it with
  this branch's `shouldSend` gate into a single options object.
- The hub settings route moved to a unified `updateSettings` transaction.
  `autoBridgeTransientModelErrors` is applied outside that transaction because
  SyncEngine owns its CLI fan-out and rollback under its own lock.

via [HAPI](https://hapi.run)

Co-authored-by: HAPI <noreply@hapi.run>
This commit is contained in:
HeavyGee
2026-11-13 18:50:09 +08:00
committed by GitHub
co-authored by HAPI
parent a7e472bb39
commit f0ab4ba79d
87 changed files with 9410 additions and 257 deletions
+20 -1
View File
@@ -72,7 +72,9 @@ export type CliMessagesResponse = z.infer<typeof CliMessagesResponseSchema>
export const CreateSessionResponseSchema = z.object({
session: SessionSchema,
/** Hub opt-in for AGENT_NOTIFY_SUMMARY prompt injection (default off when omitted). */
sessionSummaryContract: z.boolean().optional()
sessionSummaryContract: z.boolean().optional(),
/** Hub opt-in: Cursor auto-bridge after transient model errors (default off). */
autoBridgeTransientModelErrors: z.boolean().optional()
})
export type CreateSessionResponse = z.infer<typeof CreateSessionResponseSchema>
@@ -81,6 +83,7 @@ export const HubSettingsResponseSchema = z.object({
sessionSummaryContract: z.boolean(),
/** Show compact AGENT_NOTIFY_SUMMARY in chat (default off / hide). */
sessionSummaryInChat: z.boolean(),
autoBridgeTransientModelErrors: z.boolean(),
peerSpawnDefaults: ResolvedPeerSpawnDefaultsSchema
})
@@ -90,12 +93,14 @@ export const UpdateHubSettingsRequestSchema = z
.object({
sessionSummaryContract: z.boolean().optional(),
sessionSummaryInChat: z.boolean().optional(),
autoBridgeTransientModelErrors: z.boolean().optional(),
peerSpawnDefaults: PeerSpawnDefaultsSchema.optional()
})
.refine(
(data) =>
data.sessionSummaryContract !== undefined
|| data.sessionSummaryInChat !== undefined
|| data.autoBridgeTransientModelErrors !== undefined
|| data.peerSpawnDefaults !== undefined,
{ message: 'At least one hub setting field is required' }
)
@@ -549,6 +554,20 @@ export const ScratchlistEntryUpdateRequestSchema = z.object({
export type ScratchlistEntryUpdateRequest = z.infer<typeof ScratchlistEntryUpdateRequestSchema>
/** Dismiss the model-error banner for a specific displayed error (by eventId). */
export const AcknowledgeModelErrorRequestSchema = z.object({
eventId: z.string().min(1)
})
export type AcknowledgeModelErrorRequest = z.infer<typeof AcknowledgeModelErrorRequestSchema>
/** Bridge & retry for the specific displayed model error (by eventId). */
export const BridgeModelErrorRequestSchema = z.object({
eventId: z.string().min(1)
})
export type BridgeModelErrorRequest = z.infer<typeof BridgeModelErrorRequestSchema>
/** Per-session legacy stream-json → ACP migrator request. See tiann/hapi#824. */
export const CursorMigrateToAcpRequestSchema = z.object({
/** Skip removing the legacy ~/.cursor/chats source store.db even after verify passes. */
+1
View File
@@ -73,6 +73,7 @@ export const RPC_METHODS = {
RewindConversation: 'rewind-conversation',
ClearConversation: 'clear-conversation',
ImplementCodexPlan: 'implement-codex-plan',
BridgeModelError: 'bridge-model-error'
} as const
export const RPC_TARGET_MISSING_ERROR_CODE = 'rpc_target_missing' as const
+27 -1
View File
@@ -249,7 +249,33 @@ export const MetadataSchema = z.object({
// field stores only modelId (shared across all flavors); this preserves
// the provider so web can resolve the exact model when two providers
// share a modelId.
piSelectedModel: z.object({ provider: z.string(), modelId: z.string() }).nullable().optional()
piSelectedModel: z.object({ provider: z.string(), modelId: z.string() }).nullable().optional(),
lastModelError: z.object({
/** Stable identity for this error event (not wall-clock order). */
eventId: z.string().min(1),
kind: z.string(),
transient: z.boolean(),
rawSnippet: z.string(),
/** Display / telemetry timestamp only — not used for notify/ack identity. */
atTs: z.number(),
priorAssistantClaimsDone: z.boolean(),
lastUserMessage: z.string().optional(),
bridgedForEventId: z.string().optional(),
retriedAndFailed: z.boolean().optional(),
/**
* Set when a non-bridge user turn starts after this error was recorded.
* Blocks Bridge so a later retry cannot replay work the newer turn already handled.
*/
supersededByUserTurn: z.boolean().optional(),
/**
* Explicit false blocks Bridge (idle stderr after a successful turn).
* Omitted / true keeps the existing transient gate.
*/
bridgeable: z.boolean().optional(),
acknowledgedAt: z.number().optional(),
/** Hub-owned: successful push/FCM/Telegram delivery watermark. */
notifiedAt: z.number().optional()
}).optional()
})
export type Metadata = z.infer<typeof MetadataSchema>
+18
View File
@@ -380,6 +380,24 @@ describe('summary derivation helpers', () => {
expect(summary?.agentSessionId).toBe('cursor-xyz')
})
it('toSessionSummaryMetadata omits lastModelError.lastUserMessage', () => {
const summary = toSessionSummaryMetadata({
path: '/p',
host: 'h',
lastModelError: {
eventId: 'evt-1',
kind: 'transport_closed',
transient: true,
rawSnippet: 'WritableIterable is closed',
atTs: 1,
priorAssistantClaimsDone: false,
lastUserMessage: 'secret prompt text that must not leak into list payloads'
}
})
expect(summary?.lastModelError?.eventId).toBe('evt-1')
expect(summary?.lastModelError).not.toHaveProperty('lastUserMessage')
})
it('carries current-fork capability into list summaries', () => {
const summary = toSessionSummaryMetadata({
path: '/p',
+26 -1
View File
@@ -71,6 +71,20 @@ export type SessionSummaryMetadata = {
conversationHistory?: ConversationHistoryCapabilities
/** Loopback MCP URL when session CLI happy server is running (#956). */
hapiMcpUrl?: string
lastModelError?: {
eventId: string
kind: string
transient: boolean
rawSnippet: string
atTs: number
priorAssistantClaimsDone: boolean
bridgedForEventId?: string
retriedAndFailed?: boolean
supersededByUserTurn?: boolean
bridgeable?: boolean
acknowledgedAt?: number
notifiedAt?: number
}
}
export type SessionSummary = {
@@ -245,7 +259,18 @@ export function toSessionSummaryMetadata(metadata: Metadata | null | undefined):
agentSessionId: getSummaryAgentSessionId(metadata),
lifecycleState: metadata.lifecycleState,
conversationHistory: metadata.capabilities?.conversationHistory,
hapiMcpUrl: metadata.hapiMcpUrl ?? undefined
hapiMcpUrl: metadata.hapiMcpUrl ?? undefined,
// Omit lastUserMessage — bridge recovery text stays in full session
// metadata only; list/SSE summaries must not ship up to 32 KB of prompt.
lastModelError: metadata.lastModelError
? (() => {
const {
lastUserMessage: _omitLastUserMessage,
...summaryError
} = metadata.lastModelError
return summaryError
})()
: undefined
}
}