mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
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:
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,583 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
classifyAcpRpcRejection,
|
||||
classifyCursorAgentMessage,
|
||||
isCompletionClaim,
|
||||
mapAcpStderrToFailure,
|
||||
rawSnippetForFailure
|
||||
} from './cursorAgentMessageClassifier'
|
||||
|
||||
describe('classifyCursorAgentMessage', () => {
|
||||
it('classifies resource_exhausted', () => {
|
||||
const result = classifyCursorAgentMessage('Error: T: [resource_exhausted] quota exceeded')
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('quota_exhausted')
|
||||
expect(result?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies canceled', () => {
|
||||
const result = classifyCursorAgentMessage('Error: T: [canceled] the request was cancelled')
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('canceled')
|
||||
expect(result?.transient).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies deadline_exceeded', () => {
|
||||
const result = classifyCursorAgentMessage('Error: T: [deadline_exceeded]')
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('deadline_exceeded')
|
||||
expect(result?.transient).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies unavailable', () => {
|
||||
const result = classifyCursorAgentMessage('Error: T: [unavailable] service is down')
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('unavailable')
|
||||
expect(result?.transient).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies connection_stalled', () => {
|
||||
const result = classifyCursorAgentMessage('Error: T: Connection stalled after 30s')
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('connection_stalled')
|
||||
expect(result?.transient).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies context_window', () => {
|
||||
const result = classifyCursorAgentMessage(
|
||||
'Gemini prompt failed: token count exceeds the model limit'
|
||||
)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('context_window')
|
||||
expect(result?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies capacity_exhausted', () => {
|
||||
const result = classifyCursorAgentMessage(
|
||||
'Gemini prompt failed: you have exhausted your capacity for today'
|
||||
)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('capacity_exhausted')
|
||||
expect(result?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies unknown_t_prefix for unrecognised Error: T: variants', () => {
|
||||
const result = classifyCursorAgentMessage('Error: T: [some_new_error] weird thing happened')
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('unknown_t_prefix')
|
||||
expect(result?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('preserves raw text', () => {
|
||||
const raw = 'Error: T: [canceled] something something'
|
||||
const result = classifyCursorAgentMessage(raw)
|
||||
expect(result?.raw).toBe(raw)
|
||||
})
|
||||
|
||||
it('returns null for benign messages', () => {
|
||||
expect(classifyCursorAgentMessage("Here's the diff:")).toBeNull()
|
||||
expect(classifyCursorAgentMessage('Done.')).toBeNull()
|
||||
expect(classifyCursorAgentMessage('All done.')).toBeNull()
|
||||
expect(classifyCursorAgentMessage('I found 3 files.')).toBeNull()
|
||||
expect(classifyCursorAgentMessage('Successfully updated the config.')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for empty string', () => {
|
||||
expect(classifyCursorAgentMessage('')).toBeNull()
|
||||
})
|
||||
|
||||
it('is case-insensitive for Error: T: patterns', () => {
|
||||
const result = classifyCursorAgentMessage('error: t: [resource_exhausted]')
|
||||
expect(result?.kind).toBe('quota_exhausted')
|
||||
})
|
||||
|
||||
it('does not match Error: T: patterns in the middle of text', () => {
|
||||
// These patterns are anchored at the start
|
||||
expect(classifyCursorAgentMessage('Partial text before Error: T: [canceled]')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not classify prose that describes the pattern', () => {
|
||||
// Regression: 2026-06-12 self-own. The classifier matched an
|
||||
// assistant message that *described* the patterns it looks for,
|
||||
// because the original Gemini patterns used unanchored "contains".
|
||||
// Real cursor-agent error emits come as the whole message body,
|
||||
// not embedded in narrative prose. Anchored patterns reject prose.
|
||||
const proseDescribingPatterns =
|
||||
"Yes. In the soup since 23:51:24 BST.\n\n" +
|
||||
"Triggers on:\n" +
|
||||
" - Error: T: [resource_exhausted]\n" +
|
||||
" - Error: T: Connection stalled\n" +
|
||||
" - Gemini prompt failed: .*token count exceeds\n" +
|
||||
" - Gemini prompt failed: .*exhausted your capacity\n"
|
||||
expect(classifyCursorAgentMessage(proseDescribingPatterns)).toBeNull()
|
||||
|
||||
// Same idea, single line embedding the literal description.
|
||||
expect(
|
||||
classifyCursorAgentMessage(
|
||||
'The classifier looks for "Gemini prompt failed: .*token count exceeds" specifically.'
|
||||
)
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores Error: T: / RetriableError examples inside markdown fences', () => {
|
||||
const fencedQuota =
|
||||
'Here is what the wire looks like:\n' +
|
||||
'```\n' +
|
||||
'Error: T: [resource_exhausted] capacity exceeded\n' +
|
||||
'```\n' +
|
||||
'Do not treat that quote as a live failure.'
|
||||
expect(classifyCursorAgentMessage(fencedQuota)).toBeNull()
|
||||
|
||||
const fencedRetriable =
|
||||
'Example:\n' +
|
||||
'~~~\n' +
|
||||
'Error: RetriableError: Connection stalled after 30s\n' +
|
||||
'~~~\n'
|
||||
expect(classifyCursorAgentMessage(fencedRetriable)).toBeNull()
|
||||
|
||||
// Four-backtick outer fence quoting a triple-backtick example must
|
||||
// not close early on the inner ``` and leak Error: T: into classify.
|
||||
const nestedFence =
|
||||
'Docs sample:\n' +
|
||||
'````markdown\n' +
|
||||
'```\n' +
|
||||
'Error: T: [resource_exhausted] capacity exceeded\n' +
|
||||
'```\n' +
|
||||
'````\n'
|
||||
expect(classifyCursorAgentMessage(nestedFence)).toBeNull()
|
||||
|
||||
// Unclosed fence + failure tail must still classify (truncated generation).
|
||||
const truncatedFence =
|
||||
'```ts\n' +
|
||||
'partial code\n' +
|
||||
'\n' +
|
||||
'Error: T: [resource_exhausted] Error\n'
|
||||
expect(classifyCursorAgentMessage(truncatedFence)?.kind).toBe('quota_exhausted')
|
||||
|
||||
// Same-length marker WITH info string is not a closer — keep fenced.
|
||||
const fakeCloser =
|
||||
'```\n' +
|
||||
'quoted example\n' +
|
||||
'```ts\n' +
|
||||
'Error: T: [resource_exhausted] capacity exceeded\n' +
|
||||
'```\n'
|
||||
expect(classifyCursorAgentMessage(fakeCloser)).toBeNull()
|
||||
|
||||
// CRLF closers must still close (otherwise fenced Error: T: leaks).
|
||||
const crlfFence =
|
||||
'```\r\n' +
|
||||
'Error: T: [resource_exhausted] capacity exceeded\r\n' +
|
||||
'```\r\n'
|
||||
expect(classifyCursorAgentMessage(crlfFence)).toBeNull()
|
||||
|
||||
// CommonMark indented code (4+ spaces, or 0–3 spaces + tab) is not live.
|
||||
expect(
|
||||
classifyCursorAgentMessage(' Error: T: [resource_exhausted] capacity exceeded')
|
||||
).toBeNull()
|
||||
expect(
|
||||
classifyCursorAgentMessage('\tError: RetriableError: Connection stalled after 30s')
|
||||
).toBeNull()
|
||||
expect(
|
||||
classifyCursorAgentMessage(' \tError: T: [resource_exhausted] capacity exceeded')
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('still classifies real Gemini errors when they ARE the message body', () => {
|
||||
// Whitespace prefix is OK (trimStart handles it) but prose prefix is not.
|
||||
expect(
|
||||
classifyCursorAgentMessage(
|
||||
' Gemini prompt failed: token count exceeds limit'
|
||||
)?.kind
|
||||
).toBe('context_window')
|
||||
expect(
|
||||
classifyCursorAgentMessage(
|
||||
'Gemini prompt failed: you have exhausted your capacity'
|
||||
)?.kind
|
||||
).toBe('capacity_exhausted')
|
||||
})
|
||||
|
||||
it('classifies Error: T: patterns with leading whitespace (real wire format)', () => {
|
||||
// Regression: 2026-06-12 session b52b9117. Cursor ACP transport
|
||||
// emitted "\n\nError: T: WritableIterable is closed" — leading
|
||||
// newlines made the unanchored-tolerant `^Error: T:` regex miss
|
||||
// it because JS `^` matches start of string, not start of line
|
||||
// (without the `m` flag). trimStart() before the test fixes it.
|
||||
const realWireFormat = '\n\nError: T: WritableIterable is closed'
|
||||
const result = classifyCursorAgentMessage(realWireFormat)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('unknown_t_prefix')
|
||||
expect(result?.transient).toBe(false)
|
||||
// Raw text preserved as-is (leading newlines included) so the
|
||||
// banner can show the operator exactly what arrived.
|
||||
expect(result?.raw).toBe(realWireFormat)
|
||||
})
|
||||
|
||||
it('classifies leading-whitespace variants of all Error: T: kinds', () => {
|
||||
expect(classifyCursorAgentMessage('\n\nError: T: [resource_exhausted]')?.kind).toBe('quota_exhausted')
|
||||
expect(classifyCursorAgentMessage(' Error: T: [canceled]')?.kind).toBe('canceled')
|
||||
// Tab-indented = CommonMark code (stripped). Light space pad is wire OK.
|
||||
expect(classifyCursorAgentMessage(' Error: T: [deadline_exceeded]')?.kind).toBe('deadline_exceeded')
|
||||
expect(classifyCursorAgentMessage('\n\n Error: T: [unavailable]')?.kind).toBe('unavailable')
|
||||
expect(classifyCursorAgentMessage('\nError: T: Connection stalled after 30s')?.kind).toBe('connection_stalled')
|
||||
})
|
||||
|
||||
it('classifies RetriableError prefix from cursor session (real session 0e04ebe7)', () => {
|
||||
// Regression: 2026-06-20 session 0e04ebe7 ("teams structure").
|
||||
// Cursor ACP session (metadata.flavor=cursor) but HAPI persists
|
||||
// agent text in a codex-shaped envelope via convertAgentMessage —
|
||||
// that is NOT the Codex runner. The inline error used RetriableError
|
||||
// instead of Error: T: and was followed immediately by ready.
|
||||
const realWireFormat = '\n\nError: RetriableError: [canceled] http/2 stream closed with error code CANCEL (0x8)'
|
||||
const result = classifyCursorAgentMessage(realWireFormat)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('canceled')
|
||||
expect(result?.transient).toBe(true)
|
||||
expect(result?.source).toBe('text')
|
||||
})
|
||||
|
||||
it('marks RetriableError resource_exhausted as transient for auto-bridge', () => {
|
||||
// Operator ask 2026-07-14: Cursor emits this exact wire string.
|
||||
// It already classified as quota_exhausted, but with transient:false —
|
||||
// auto-bridge only retries transient:true. RetriableError means the
|
||||
// agent labeled the failure retriable; keep Error: T: / stderr quota
|
||||
// paths non-transient.
|
||||
const exactWire = 'Error: RetriableError: [resource_exhausted] Error'
|
||||
const result = classifyCursorAgentMessage(exactWire)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('quota_exhausted')
|
||||
expect(result?.transient).toBe(true)
|
||||
expect(result?.source).toBe('text')
|
||||
expect(result?.raw).toBe(exactWire)
|
||||
})
|
||||
|
||||
it('marks RetriableError [internal] as transient for auto-bridge', () => {
|
||||
// Operator ask 2026-09-08 (videoagent / castle bumper): Cursor emitted
|
||||
// "Error: RetriableError: [internal] No exec result" and the banner
|
||||
// showed unknown_t_prefix with no auto-Bridge. Catch-all was fail-closed
|
||||
// (transient:false). RetriableError+[internal] is a Cursor-labeled
|
||||
// hiccup — treat like other RetriableError brackets. Keep bare
|
||||
// Error: T: [internal] on the non-transient catch-all.
|
||||
const exactWire = 'Error: RetriableError: [internal] No exec result'
|
||||
const result = classifyCursorAgentMessage(exactWire)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('internal')
|
||||
expect(result?.transient).toBe(true)
|
||||
expect(result?.source).toBe('text')
|
||||
expect(result?.raw).toBe(exactWire)
|
||||
|
||||
const leadingNewlines = '\n\nError: RetriableError: [internal] No exec result'
|
||||
expect(classifyCursorAgentMessage(leadingNewlines)?.kind).toBe('internal')
|
||||
expect(classifyCursorAgentMessage(leadingNewlines)?.transient).toBe(true)
|
||||
|
||||
// Error: T: form stays fail-closed (unknown catch-all).
|
||||
const tForm = 'Error: T: [internal] No exec result'
|
||||
const tResult = classifyCursorAgentMessage(tForm)
|
||||
expect(tResult?.kind).toBe('unknown_t_prefix')
|
||||
expect(tResult?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies error appended to in-flight agent text (real session e7d9b44b)', () => {
|
||||
// Regression: 2026-06-13 session e7d9b44b. cursor-agent appended
|
||||
// a gRPC stringification to the END of a normal narrative output
|
||||
// rather than rejecting the prompt. The structural signals
|
||||
// (RPC rejection / stderr) didn't fire because the agent never
|
||||
// crashed - it just dumped the error into its own text stream.
|
||||
// Start-of-string anchor missed it (text starts with prose);
|
||||
// multiline `^` (start-of-line after the `\n\n`) catches it.
|
||||
const realWireFormat =
|
||||
"Three of the four hit Codex's usage limit (#151, #153, #155) " +
|
||||
"- no code review delivered. Only #157 actually got reviewed. " +
|
||||
"Let me pull the inline comments to see Codex's specific suggestions:\n\n" +
|
||||
"Error: T: [resource_exhausted] Error"
|
||||
const result = classifyCursorAgentMessage(realWireFormat)
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.kind).toBe('quota_exhausted')
|
||||
expect(result?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('still rejects bullet-listed pattern descriptions (no false positive)', () => {
|
||||
// Lines indented with whitespace+dash do NOT start with "Error:" -
|
||||
// multiline `^` requires the line to literally begin with the
|
||||
// pattern. Self-own from 2026-06-12 stays prevented.
|
||||
const proseDescribingPatterns =
|
||||
"Yes. In the soup since 23:51:24 BST.\n\n" +
|
||||
"Triggers on:\n" +
|
||||
" - Error: T: [resource_exhausted]\n" +
|
||||
" - Error: T: Connection stalled\n" +
|
||||
" - Gemini prompt failed: .*token count exceeds\n" +
|
||||
" - Gemini prompt failed: .*exhausted your capacity\n"
|
||||
expect(classifyCursorAgentMessage(proseDescribingPatterns)).toBeNull()
|
||||
})
|
||||
|
||||
it('catches all gRPC kinds when appended after prose+newlines', () => {
|
||||
const prefix = "Working on the task. Got partial results before failure:\n\n"
|
||||
expect(classifyCursorAgentMessage(prefix + 'Error: T: [resource_exhausted] Error')?.kind).toBe('quota_exhausted')
|
||||
expect(classifyCursorAgentMessage(prefix + 'Error: T: [canceled] Operation aborted')?.kind).toBe('canceled')
|
||||
expect(classifyCursorAgentMessage(prefix + 'Error: T: [deadline_exceeded]')?.kind).toBe('deadline_exceeded')
|
||||
expect(classifyCursorAgentMessage(prefix + 'Error: T: [unavailable] Service down')?.kind).toBe('unavailable')
|
||||
expect(classifyCursorAgentMessage(prefix + 'Error: T: Connection stalled')?.kind).toBe('connection_stalled')
|
||||
expect(classifyCursorAgentMessage(prefix + 'Error: T: WritableIterable is closed')?.kind).toBe('unknown_t_prefix')
|
||||
expect(classifyCursorAgentMessage(prefix + 'Gemini prompt failed: token count exceeds 1M')?.kind).toBe('context_window')
|
||||
expect(classifyCursorAgentMessage(prefix + 'Gemini prompt failed: exhausted your capacity')?.kind).toBe('capacity_exhausted')
|
||||
})
|
||||
|
||||
it("tags text-classifier results with source='text'", () => {
|
||||
const result = classifyCursorAgentMessage('Error: T: [canceled]')
|
||||
expect(result?.source).toBe('text')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mapAcpStderrToFailure (structural stderr signal)', () => {
|
||||
it('maps rate_limit -> rate_limited (transient)', () => {
|
||||
const out = mapAcpStderrToFailure({ type: 'rate_limit', raw: 'status 429 ratelimitexceeded' })
|
||||
expect(out).not.toBeNull()
|
||||
expect(out!.kind).toBe('rate_limited')
|
||||
expect(out!.transient).toBe(true)
|
||||
expect(out!.source).toBe('stderr')
|
||||
expect(out!.raw).toBe('status 429 ratelimitexceeded')
|
||||
})
|
||||
|
||||
it('maps quota_exceeded -> quota_exhausted (non-transient)', () => {
|
||||
const out = mapAcpStderrToFailure({ type: 'quota_exceeded', raw: 'resource exhausted' })
|
||||
expect(out).not.toBeNull()
|
||||
expect(out!.kind).toBe('quota_exhausted')
|
||||
expect(out!.transient).toBe(false)
|
||||
expect(out!.source).toBe('stderr')
|
||||
})
|
||||
|
||||
it('maps authentication -> auth_failed (non-transient)', () => {
|
||||
const out = mapAcpStderrToFailure({ type: 'authentication', raw: 'status 401 unauthenticated' })
|
||||
expect(out).not.toBeNull()
|
||||
expect(out!.kind).toBe('auth_failed')
|
||||
expect(out!.transient).toBe(false)
|
||||
expect(out!.source).toBe('stderr')
|
||||
})
|
||||
|
||||
it('maps model_not_found -> model_not_found (non-transient)', () => {
|
||||
const out = mapAcpStderrToFailure({ type: 'model_not_found', raw: 'status 404 model not found' })
|
||||
expect(out).not.toBeNull()
|
||||
expect(out!.kind).toBe('model_not_found')
|
||||
expect(out!.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('maps Cursor Cannot use this model rejection', () => {
|
||||
const out = mapAcpStderrToFailure({
|
||||
type: 'model_not_found',
|
||||
raw: 'Cannot use this model: grok-4.5[fast=true]. Available models: auto'
|
||||
})
|
||||
expect(out?.kind).toBe('model_not_found')
|
||||
})
|
||||
|
||||
it('ignores unknown stderr (status-only; do not promote to modelError)', () => {
|
||||
// Transport emits type:unknown for any stderr containing error/failed/
|
||||
// exception — too broad for urgent model-error alerts.
|
||||
const out = mapAcpStderrToFailure({ type: 'unknown', raw: 'unexpected exception in agent' })
|
||||
expect(out).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores weak typed stderr that only matches transport substrings', () => {
|
||||
expect(mapAcpStderrToFailure({
|
||||
type: 'authentication',
|
||||
raw: 'authentication provider initialized'
|
||||
})).toBeNull()
|
||||
expect(mapAcpStderrToFailure({
|
||||
type: 'rate_limit',
|
||||
raw: 'checking rate limit configuration'
|
||||
})).toBeNull()
|
||||
expect(mapAcpStderrToFailure({
|
||||
type: 'quota_exceeded',
|
||||
raw: 'quota tracker warmed up'
|
||||
})).toBeNull()
|
||||
expect(mapAcpStderrToFailure({
|
||||
type: 'model_not_found',
|
||||
raw: 'catalog refresh skipped for unknown models'
|
||||
})).toBeNull()
|
||||
expect(mapAcpStderrToFailure({
|
||||
type: 'authentication',
|
||||
raw: 'failed to read config: permission denied'
|
||||
})).toBeNull()
|
||||
expect(mapAcpStderrToFailure({
|
||||
type: 'model_not_found',
|
||||
raw: 'plugin cache entry not_found'
|
||||
})).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('classifyAcpRpcRejection (structural RPC signal)', () => {
|
||||
it('classifies WritableIterable is closed -> transport_closed (non-bridgeable)', () => {
|
||||
// Real session b52b9117: the agent rejected sendRequest with this
|
||||
// exact message after the writable side of the ACP transport died.
|
||||
const err = new Error('WritableIterable is closed')
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out).not.toBeNull()
|
||||
expect(out?.kind).toBe('transport_closed')
|
||||
expect(out?.transient).toBe(false)
|
||||
expect(out?.source).toBe('rpc')
|
||||
})
|
||||
|
||||
it('classifies ACP transport closed -> transport_closed (non-bridgeable)', () => {
|
||||
const err = new Error('ACP transport is closed')
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out?.kind).toBe('transport_closed')
|
||||
expect(out?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies process exit -> transport_closed (rejectAllPending pathway)', () => {
|
||||
// markClosed wraps the process-exit message in a new Error; pending
|
||||
// sendRequests reject with that error.
|
||||
const err = new Error('ACP process exited (code=137, signal=SIGKILL)')
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out?.kind).toBe('transport_closed')
|
||||
expect(out?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies spawn failure -> agent_crashed (non-bridgeable)', () => {
|
||||
const err = new Error('Failed to spawn cursor-agent: ENOENT. Is it installed and on PATH?')
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out?.kind).toBe('agent_crashed')
|
||||
expect(out?.transient).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies request timeout -> rpc_timeout', () => {
|
||||
const err = new Error("ACP request 'session/prompt' timed out after 120000ms")
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out?.kind).toBe('rpc_timeout')
|
||||
expect(out?.transient).toBe(true)
|
||||
})
|
||||
|
||||
it('returns null for user cancellations (NOT model errors)', () => {
|
||||
expect(classifyAcpRpcRejection(new Error('Aborted by user'))).toBeNull()
|
||||
expect(classifyAcpRpcRejection(new Error('user cancelled the request'))).toBeNull()
|
||||
expect(classifyAcpRpcRejection(new Error('user canceled the request'))).toBeNull()
|
||||
})
|
||||
|
||||
it('passes through gRPC-status RPC errors with source=rpc', () => {
|
||||
// Cursor-agent sometimes returns the gRPC status as a JSON-RPC
|
||||
// error.message rather than emitting it as a text message.
|
||||
const err = new Error('Error: T: [resource_exhausted] quota exceeded')
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out?.kind).toBe('quota_exhausted')
|
||||
expect(out?.transient).toBe(false)
|
||||
// The structural source overrides text classification's source tag.
|
||||
expect(out?.source).toBe('rpc')
|
||||
})
|
||||
|
||||
it('classifies [canceled] Operation aborted via text path before user-abort filter', () => {
|
||||
// Bare "aborted" must not null out real gRPC canceled shapes that
|
||||
// happen to include that word in the status message.
|
||||
const err = new Error('Error: T: [canceled] Operation aborted')
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out).not.toBeNull()
|
||||
expect(out?.kind).toBe('canceled')
|
||||
expect(out?.source).toBe('rpc')
|
||||
})
|
||||
|
||||
it('classifies plain Rate limit exceeded RPC messages as transient', () => {
|
||||
const out = classifyAcpRpcRejection(new Error('Rate limit exceeded'))
|
||||
expect(out?.kind).toBe('rate_limited')
|
||||
expect(out?.transient).toBe(true)
|
||||
expect(out?.source).toBe('rpc')
|
||||
})
|
||||
|
||||
it('classifies status 429 RPC messages as transient', () => {
|
||||
const out = classifyAcpRpcRejection(new Error('status 429 ratelimitexceeded'))
|
||||
expect(out?.kind).toBe('rate_limited')
|
||||
expect(out?.transient).toBe(true)
|
||||
expect(out?.source).toBe('rpc')
|
||||
})
|
||||
|
||||
it('falls through to prompt_failed for unrecognised RPC errors', () => {
|
||||
const err = new Error('Some weird internal SDK assertion failed')
|
||||
const out = classifyAcpRpcRejection(err)
|
||||
expect(out?.kind).toBe('prompt_failed')
|
||||
expect(out?.transient).toBe(false)
|
||||
expect(out?.source).toBe('rpc')
|
||||
})
|
||||
|
||||
it('handles non-Error rejection values', () => {
|
||||
const out = classifyAcpRpcRejection('plain string rejection')
|
||||
expect(out?.kind).toBe('prompt_failed')
|
||||
expect(out?.raw).toBe('plain string rejection')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isCompletionClaim', () => {
|
||||
it('matches Done', () => expect(isCompletionClaim('Done.')).toBe(true))
|
||||
it('matches All done', () => expect(isCompletionClaim('All done. The PR is filed.')).toBe(true))
|
||||
it('matches Committed', () => expect(isCompletionClaim('Committed all changes.')).toBe(true))
|
||||
it('matches Successfully completed', () => expect(isCompletionClaim('Successfully completed the migration.')).toBe(true))
|
||||
it('matches Successfully fixed', () => expect(isCompletionClaim('Successfully fixed the bug.')).toBe(true))
|
||||
it('matches Fixed', () => expect(isCompletionClaim('Fixed the bug.')).toBe(true))
|
||||
it('matches Complete', () => expect(isCompletionClaim('Complete.')).toBe(true))
|
||||
it('matches Completed', () => expect(isCompletionClaim('Completed.')).toBe(true))
|
||||
it('is case-insensitive', () => {
|
||||
expect(isCompletionClaim('DONE everything')).toBe(true)
|
||||
expect(isCompletionClaim('all done')).toBe(true)
|
||||
})
|
||||
it('matches Done when Error: T is appended to the same block', () => {
|
||||
// Cursor free-text path: completion claim + gRPC error in one message.
|
||||
expect(isCompletionClaim(
|
||||
'Done.\n\nError: T: [canceled] Operation aborted'
|
||||
)).toBe(true)
|
||||
})
|
||||
it('does not match non-completion phrases', () => {
|
||||
expect(isCompletionClaim("Here's the plan")).toBe(false)
|
||||
expect(isCompletionClaim("I'm working on it")).toBe(false)
|
||||
})
|
||||
it('does not match Completely… as a completion claim', () => {
|
||||
expect(isCompletionClaim('Completely unable to finish the task.')).toBe(false)
|
||||
})
|
||||
it('does not match Successfully reproduced… as a completion claim', () => {
|
||||
expect(isCompletionClaim('Successfully reproduced the issue, but the fix is pending.')).toBe(false)
|
||||
})
|
||||
it('handles empty string', () => {
|
||||
expect(isCompletionClaim('')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rawSnippetForFailure', () => {
|
||||
it('slices from Error: T marker when prose exceeds 400 chars', () => {
|
||||
const prose = 'A'.repeat(450)
|
||||
const failure = {
|
||||
kind: 'canceled' as const,
|
||||
transient: true,
|
||||
raw: `${prose}\n\nError: T: [canceled] Operation aborted`,
|
||||
source: 'text' as const
|
||||
}
|
||||
const snippet = rawSnippetForFailure(failure)
|
||||
expect(snippet.startsWith('Error: T:')).toBe(true)
|
||||
expect(snippet).toContain('[canceled]')
|
||||
expect(snippet.length).toBeLessThanOrEqual(400)
|
||||
})
|
||||
|
||||
it('keeps start-of-string for non-text sources', () => {
|
||||
const failure = {
|
||||
kind: 'rate_limited' as const,
|
||||
transient: true,
|
||||
raw: 'status 429 ratelimitexceeded',
|
||||
source: 'stderr' as const
|
||||
}
|
||||
expect(rawSnippetForFailure(failure)).toBe('status 429 ratelimitexceeded')
|
||||
})
|
||||
|
||||
it('prefers the last Error: T marker over an earlier fenced example', () => {
|
||||
const filler = 'x'.repeat(450)
|
||||
const raw = [
|
||||
'Here is an example of a failure:',
|
||||
'```',
|
||||
'Error: T: [canceled] example only',
|
||||
'```',
|
||||
filler,
|
||||
'Error: T: [resource_exhausted] real failure'
|
||||
].join('\n')
|
||||
const failure = {
|
||||
kind: 'quota_exhausted' as const,
|
||||
transient: true,
|
||||
raw,
|
||||
source: 'text' as const
|
||||
}
|
||||
const snippet = rawSnippetForFailure(failure)
|
||||
expect(snippet.startsWith('Error: T: [resource_exhausted]')).toBe(true)
|
||||
expect(snippet).not.toContain('example only')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,399 @@
|
||||
/**
|
||||
* Structural-first classifier for cursor-agent failure signals.
|
||||
*
|
||||
* Sources, in priority order:
|
||||
* 1. JSON-RPC rejection on session/prompt (structural: thrown Error from
|
||||
* `@zed-industries/agent-client-protocol` SDK or transport close).
|
||||
* 2. Stderr lines parsed by AcpStdioTransport into typed AcpStderrError.
|
||||
* 3. Text in agent/message events (last-resort fallback, brittle by nature
|
||||
* because cursor-agent stringifies internal errors as plain prose).
|
||||
*
|
||||
* The text fallback (1)-(3) only fires when no structural signal already
|
||||
* classified the turn. Each source carries a `source` tag so the operator
|
||||
* (and tests) can tell where the classification came from.
|
||||
*/
|
||||
export type CursorAgentStreamFailureKind =
|
||||
// --- text/agent-message classifier kinds (legacy, fallback) ---
|
||||
| 'quota_exhausted'
|
||||
| 'canceled'
|
||||
| 'deadline_exceeded'
|
||||
| 'unavailable'
|
||||
| 'connection_stalled'
|
||||
| 'internal' // RetriableError: [internal] (Cursor-labeled hiccup)
|
||||
| 'context_window'
|
||||
| 'capacity_exhausted'
|
||||
| 'unknown_t_prefix'
|
||||
// --- structural kinds ---
|
||||
| 'transport_closed' // ACP transport closed mid-turn (WritableIterable, etc.)
|
||||
| 'rpc_timeout' // sendRequest timeout
|
||||
| 'rpc_error' // JSON-RPC error response from the agent
|
||||
| 'agent_crashed' // process exit during in-flight prompt
|
||||
| 'rate_limited' // stderr-derived rate limit
|
||||
| 'auth_failed' // stderr-derived authentication failure
|
||||
| 'model_not_found' // stderr-derived model-not-found
|
||||
| 'unknown_stderr' // stderr line classified as error but not typed
|
||||
| 'prompt_failed' // catch-all for prompt rejections
|
||||
|
||||
export type CursorAgentStreamFailureSource = 'rpc' | 'stderr' | 'text'
|
||||
|
||||
export type CursorAgentStreamFailure = {
|
||||
kind: CursorAgentStreamFailureKind
|
||||
transient: boolean
|
||||
raw: string
|
||||
source: CursorAgentStreamFailureSource
|
||||
}
|
||||
|
||||
type Pattern = {
|
||||
test: (text: string) => boolean
|
||||
kind: CursorAgentStreamFailureKind
|
||||
transient: boolean
|
||||
}
|
||||
|
||||
// Patterns are anchored to the start of A LINE (multiline `m` flag), not
|
||||
// just start-of-string. Three real cursor-agent failure shapes drove this:
|
||||
//
|
||||
// 1. Whole-body emit (session b52b9117, 2026-06-12):
|
||||
// "\n\nError: T: WritableIterable is closed"
|
||||
// -- start of message, after leading whitespace.
|
||||
//
|
||||
// 2. Mid-stream append (session e7d9b44b, 2026-06-13):
|
||||
// "Three of the four hit Codex's usage limit (#151, #153, #155) -
|
||||
// no code review delivered. Only #157 actually got reviewed.
|
||||
// Let me pull the inline comments to see Codex's specific
|
||||
// suggestions:\n\nError: T: [resource_exhausted] Error"
|
||||
// -- cursor-agent appended the gRPC status to the END of an in-flight
|
||||
// text stream rather than rejecting the prompt. Start-of-line `m`
|
||||
// anchor catches this: the `\n\n` separator means `Error: T:` is at
|
||||
// the start of a new line. Pure start-of-string anchoring missed it.
|
||||
//
|
||||
// 3. Prose that DESCRIBES the patterns (2026-06-12 self-own):
|
||||
// "Triggers on:\n - Error: T: [resource_exhausted]\n - ..."
|
||||
// -- each bullet line starts with whitespace+dash, NOT with "Error:".
|
||||
// Multiline `^Error:` rejects it.
|
||||
//
|
||||
// 4. RetriableError prefix (session 0e04ebe7, 2026-06-20):
|
||||
// "\n\nError: RetriableError: [canceled] http/2 stream closed..."
|
||||
// -- same gRPC bracket notation as `Error: T:` but cursor-agent
|
||||
// sometimes stringifies via RetriableError instead. Still a Cursor
|
||||
// ACP session; HAPI persists agent messages in a codex-shaped
|
||||
// envelope (`convertAgentMessage`) which is NOT the Codex runner.
|
||||
//
|
||||
// The diagnostic strength is in the `[snake_case]` bracket form (gRPC's
|
||||
// stable status notation) and `Error: T:` prefix - both characteristic of
|
||||
// cursor-agent's runtime stringification, rare in genuine prose. The
|
||||
// catch-all `Error: T:` is intentionally narrow enough that benign mention
|
||||
// would have to literally start a line with "Error: T:" - documented
|
||||
// trade-off, the false-positive surface is small and recoverable
|
||||
// (operator dismisses banner). The miss surface (this exact failure
|
||||
// class going unflagged) is much worse.
|
||||
// `^[ \t]*` allows horizontal whitespace before the marker (covers
|
||||
// session b52b9117's " Error: T: [canceled]" wire format with leading
|
||||
// spaces). It does NOT allow `\n` consumption, so multi-line strings
|
||||
// only match where the marker actually sits at the start of a line.
|
||||
// Bullet-list prose like " - Error: T: ..." still rejects: after
|
||||
// `[ \t]*` consumes the spaces, the next char is `-`, not `Error`.
|
||||
const PATTERNS: Pattern[] = [
|
||||
// RetriableError resource_exhausted is auto-bridgeable: cursor-agent
|
||||
// labeled the failure RetriableError, so mark transient:true. Keep the
|
||||
// `Error: T:` form (and stderr quota_exceeded mapping) non-transient —
|
||||
// those are harder quota / capacity stops, not hiccups.
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: RetriableError: \[resource_exhausted\]/im.test(t),
|
||||
kind: 'quota_exhausted',
|
||||
transient: true
|
||||
},
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: T: \[resource_exhausted\]/im.test(t),
|
||||
kind: 'quota_exhausted',
|
||||
transient: false
|
||||
},
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: T: \[canceled\]/im.test(t)
|
||||
|| /^[ \t]*Error: RetriableError: \[canceled\]/im.test(t),
|
||||
kind: 'canceled',
|
||||
transient: true
|
||||
},
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: T: \[deadline_exceeded\]/im.test(t)
|
||||
|| /^[ \t]*Error: RetriableError: \[deadline_exceeded\]/im.test(t),
|
||||
kind: 'deadline_exceeded',
|
||||
transient: true
|
||||
},
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: T: \[unavailable\]/im.test(t)
|
||||
|| /^[ \t]*Error: RetriableError: \[unavailable\]/im.test(t),
|
||||
kind: 'unavailable',
|
||||
transient: true
|
||||
},
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: T: Connection stalled/im.test(t)
|
||||
|| /^[ \t]*Error: RetriableError: Connection stalled/im.test(t),
|
||||
kind: 'connection_stalled',
|
||||
transient: true
|
||||
},
|
||||
// RetriableError [internal] only — Cursor labeled the failure retriable
|
||||
// (dogfood 2026-09-08: "No exec result"). Keep Error: T: [internal] on
|
||||
// the non-transient catch-all, same split as resource_exhausted.
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: RetriableError: \[internal\]/im.test(t),
|
||||
kind: 'internal',
|
||||
transient: true
|
||||
},
|
||||
{
|
||||
test: (t) => /^[ \t]*Gemini prompt failed:.*token count exceeds/im.test(t),
|
||||
kind: 'context_window',
|
||||
transient: false
|
||||
},
|
||||
{
|
||||
test: (t) => /^[ \t]*Gemini prompt failed:.*exhausted your capacity/im.test(t),
|
||||
kind: 'capacity_exhausted',
|
||||
transient: false
|
||||
},
|
||||
// catch-all for unknown `Error: T:` / `Error: RetriableError:` prefixes — placed last
|
||||
{
|
||||
test: (t) => /^[ \t]*Error: T:/im.test(t)
|
||||
|| /^[ \t]*Error: RetriableError:/im.test(t),
|
||||
kind: 'unknown_t_prefix',
|
||||
transient: false
|
||||
}
|
||||
]
|
||||
|
||||
/**
|
||||
* Returns a failure descriptor when the message text matches a known
|
||||
* cursor-agent inline model error pattern, or null for benign messages.
|
||||
*
|
||||
* NOTE: this is the LAST-RESORT fallback. Prefer structural signals
|
||||
* (classifyAcpRpcRejection, mapAcpStderrToFailure) — they fire before
|
||||
* this path runs and are not subject to false positives from prose that
|
||||
* happens to match the pattern shape.
|
||||
*/
|
||||
/** Drop closed markdown fenced regions so quoted Error: T: examples are not
|
||||
* classified. Tracks opener char + length (four-backtick outer ≠ closed by
|
||||
* inner ```). Unclosed fences are restored at EOF so a truncated generation
|
||||
* that ends with Error: T: is still classifiable. */
|
||||
function stripMarkdownFences(text: string): string {
|
||||
const visible: string[] = []
|
||||
let fence: { char: '`' | '~'; length: number; buffered: string[] } | null = null
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const match = line.match(/^[ \t]{0,3}(`{3,}|~{3,})/)
|
||||
if (!match) {
|
||||
if (fence) {
|
||||
fence.buffered.push(line)
|
||||
} else {
|
||||
visible.push(line)
|
||||
}
|
||||
continue
|
||||
}
|
||||
const marker = match[1]!
|
||||
const char = marker[0]! as '`' | '~'
|
||||
if (!fence) {
|
||||
fence = { char, length: marker.length, buffered: [line] }
|
||||
continue
|
||||
}
|
||||
fence.buffered.push(line)
|
||||
// Closers are bare markers only (no info string like ```ts).
|
||||
const close = line.match(/^[ \t]{0,3}(`{3,}|~{3,})[ \t]*$/)
|
||||
if (
|
||||
close
|
||||
&& close[1]![0] === fence.char
|
||||
&& close[1]!.length >= fence.length
|
||||
) {
|
||||
fence = null
|
||||
}
|
||||
}
|
||||
if (fence) {
|
||||
visible.push(...fence.buffered)
|
||||
}
|
||||
return visible.join('\n')
|
||||
}
|
||||
|
||||
/** Drop CommonMark indented-code lines so quoted Error: T: examples are not
|
||||
* treated as live wire failures. Tab stops of 4: 4+ spaces, or 0–3 spaces
|
||||
* then a tab. Keep bare 1–3 space prefixes — real ACP emits sometimes pad. */
|
||||
function stripIndentedCode(text: string): string {
|
||||
return text
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => !/^(?: {4,}| {0,3}\t)/.test(line))
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
export function classifyCursorAgentMessage(text: string): CursorAgentStreamFailure | null {
|
||||
const candidate = stripIndentedCode(stripMarkdownFences(text))
|
||||
for (const pattern of PATTERNS) {
|
||||
if (pattern.test(candidate)) {
|
||||
return { kind: pattern.kind, transient: pattern.transient, raw: text, source: 'text' }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Strong failure signatures required before promoting a typed ACP stderr
|
||||
* event to modelError. The transport assigns rate_limit / authentication /
|
||||
* quota_exceeded from bare substrings ("rate limit", "authentication",
|
||||
* "quota"), so a line like "authentication provider initialized" becomes
|
||||
* type authentication. We re-check raw text here.
|
||||
*/
|
||||
const STRONG_STDERR_PATTERNS = {
|
||||
rate_limit: /status 429|ratelimitexceeded|rate limit (?:exceeded|reached|hit)/i,
|
||||
model_not_found: /Cannot use this model:\s*\S|status 404[^\n]*\bmodel\b|model (?:is )?not found/i,
|
||||
authentication: /status (?:401|403)|\bunauthenticated\b|authentication (?:failed|required|expired)|(?:token|credential)[^\n]{0,80}permission denied/i,
|
||||
quota_exceeded: /quota (?:exceeded|exhausted|limit reached)|resource ?exhausted/i
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Maps an AcpStderrError (typed by AcpStdioTransport.parseStderrError) to
|
||||
* a CursorAgentStreamFailure when the raw text also carries a strong
|
||||
* failure signature. Accepts a minimal AcpStderrError shape so this module
|
||||
* stays decoupled from the transport package.
|
||||
*
|
||||
* Returns null for:
|
||||
* - `unknown` (transport labels any "error"/"failed"/"exception" line)
|
||||
* - typed events whose raw text is only a weak substring match
|
||||
*
|
||||
* ACP treats stderr as logging (`Clients MAY capture, forward, or ignore`);
|
||||
* urgent model-error alerts need a definitive failure signature.
|
||||
*/
|
||||
export function mapAcpStderrToFailure(error: {
|
||||
type: 'rate_limit' | 'model_not_found' | 'authentication' | 'quota_exceeded' | 'unknown'
|
||||
raw: string
|
||||
}): CursorAgentStreamFailure | null {
|
||||
if (error.type === 'unknown') {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!STRONG_STDERR_PATTERNS[error.type].test(error.raw)) {
|
||||
return null
|
||||
}
|
||||
|
||||
switch (error.type) {
|
||||
case 'rate_limit':
|
||||
return { kind: 'rate_limited', transient: true, raw: error.raw, source: 'stderr' }
|
||||
case 'model_not_found':
|
||||
return { kind: 'model_not_found', transient: false, raw: error.raw, source: 'stderr' }
|
||||
case 'authentication':
|
||||
return { kind: 'auth_failed', transient: false, raw: error.raw, source: 'stderr' }
|
||||
case 'quota_exceeded':
|
||||
return { kind: 'quota_exhausted', transient: false, raw: error.raw, source: 'stderr' }
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspects an Error thrown by `backend.prompt(...)` (i.e. the JSON-RPC
|
||||
* `session/prompt` call) and classifies it.
|
||||
*
|
||||
* The error sources are STRUCTURAL: thrown by either the
|
||||
* `@zed-industries/agent-client-protocol` SDK on transport close, or by
|
||||
* `AcpStdioTransport.markClosed` -> `rejectAllPending` on process exit /
|
||||
* stream close, or by the JSON-RPC layer on `error.message` from a typed
|
||||
* agent-side error response. We do match against `error.message` strings
|
||||
* here — but those strings are emitted by code we control or vendor, not
|
||||
* by free-text agent prose. The blast radius for false positives is the
|
||||
* library's stable error vocabulary, which is much smaller than "any
|
||||
* message a cursor-agent might emit."
|
||||
*
|
||||
* Returns null if the error doesn't look like a model-side failure
|
||||
* (e.g. user cancellation, programmer error in our own code) — the
|
||||
* caller should still log/surface the error but not fire modelError.
|
||||
*/
|
||||
export function classifyAcpRpcRejection(error: unknown): CursorAgentStreamFailure | null {
|
||||
const raw = error instanceof Error ? error.message : String(error)
|
||||
const lower = raw.toLowerCase()
|
||||
|
||||
// gRPC / agent text shapes can arrive as JSON-RPC error.message (including
|
||||
// "... [canceled] Operation aborted"). Classify those BEFORE the user-abort
|
||||
// filter — a bare `aborted` substring must not swallow real model cancels.
|
||||
const textMatch = classifyCursorAgentMessage(raw)
|
||||
if (textMatch) {
|
||||
return { ...textMatch, source: 'rpc' }
|
||||
}
|
||||
|
||||
// Programmer/user signals that should NOT fire modelError.
|
||||
if (
|
||||
lower.includes('aborted by user')
|
||||
|| lower.includes('user cancelled')
|
||||
|| lower.includes('user canceled')
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Transport-level closure: WritableIterable closed, ACP transport closed,
|
||||
// or process exited. All come through markClosed() -> rejectAllPending().
|
||||
// Not bridgeable: Bridge reuses the same backend.prompt path, and a closed
|
||||
// AcpStdioTransport rejects every subsequent sendRequest until reconnect.
|
||||
if (
|
||||
lower.includes('writableiterable is closed') ||
|
||||
lower.includes('acp transport is closed') ||
|
||||
lower.includes('acp transport closed') ||
|
||||
lower.includes('acp process exited')
|
||||
) {
|
||||
return { kind: 'transport_closed', transient: false, raw, source: 'rpc' }
|
||||
}
|
||||
|
||||
// Process error during spawn / IO failure during write.
|
||||
// Same as transport_closed: no reconnect/reload yet, so Bridge cannot recover.
|
||||
if (lower.includes('failed to spawn') || lower.includes('epipe') || lower.includes('ecanceled')) {
|
||||
return { kind: 'agent_crashed', transient: false, raw, source: 'rpc' }
|
||||
}
|
||||
|
||||
// Request-level timeout (DEFAULT_TIMEOUT_MS in AcpStdioTransport).
|
||||
if (lower.includes('timed out after') || lower.includes('timeout')) {
|
||||
return { kind: 'rpc_timeout', transient: true, raw, source: 'rpc' }
|
||||
}
|
||||
|
||||
// Plain JSON-RPC error.message (no [rate_limit] brackets). Same signatures
|
||||
// as stderr promotion so Bridge can retry structural 429s.
|
||||
if (STRONG_STDERR_PATTERNS.rate_limit.test(raw)) {
|
||||
return { kind: 'rate_limited', transient: true, raw, source: 'rpc' }
|
||||
}
|
||||
|
||||
// Catch-all: the prompt rejected for SOME reason. Conservative:
|
||||
// fire modelError as 'prompt_failed' (non-transient) so the operator
|
||||
// sees the turn was degraded.
|
||||
return { kind: 'prompt_failed', transient: false, raw, source: 'rpc' }
|
||||
}
|
||||
|
||||
const PRIOR_DONE_PATTERNS = [
|
||||
/^done(?:[.!:]|\s|$)/,
|
||||
/^all done(?:[.!:]|\s|$)/,
|
||||
/^committed(?:[.!:]|\s|$)/,
|
||||
/^fixed(?:[.!:]|\s|$)/,
|
||||
/^complete(?:d)?(?:[.!:]|\s|$)/,
|
||||
/^successfully\s+(?:completed|fixed|committed)\b/
|
||||
]
|
||||
|
||||
/**
|
||||
* Returns true when the text looks like the agent claimed task completion
|
||||
* (e.g. "Done.", "All done.", "Successfully completed.").
|
||||
* Word-boundary patterns — not startsWith — so "Completely unable…" and
|
||||
* "Successfully reproduced…" do not falsely set priorAssistantClaimsDone.
|
||||
*/
|
||||
export function isCompletionClaim(text: string): boolean {
|
||||
const lower = text.trim().toLowerCase()
|
||||
return PRIOR_DONE_PATTERNS.some((pattern) => pattern.test(lower))
|
||||
}
|
||||
|
||||
const TEXT_ERROR_MARKER = /^[ \t]*(?:Error: (?:T|RetriableError):|Gemini prompt failed:)/gim
|
||||
|
||||
/**
|
||||
* Prefer the matched error marker when slicing rawSnippet so "View raw error"
|
||||
* shows the failure, not the preceding assistant prose when Error: T: is
|
||||
* appended after a long response.
|
||||
*
|
||||
* Use the LAST marker: classifyCursorAgentMessage strips closed fences /
|
||||
* indented code before matching, so an earlier quoted example in raw text
|
||||
* must not steal the snippet from the real appended failure.
|
||||
*/
|
||||
export function rawSnippetForFailure(failure: CursorAgentStreamFailure, maxLen = 400): string {
|
||||
let start = 0
|
||||
if (failure.source === 'text') {
|
||||
const matches = Array.from(failure.raw.matchAll(TEXT_ERROR_MARKER))
|
||||
const last = matches.at(-1)
|
||||
if (typeof last?.index === 'number') {
|
||||
start = last.index
|
||||
}
|
||||
}
|
||||
return failure.raw.slice(start, start + maxLen)
|
||||
}
|
||||
@@ -21,6 +21,16 @@ import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand';
|
||||
import type { CursorStreamEvent } from './utils/cursorLegacyEventConverter';
|
||||
import { parseCursorEvent, convertCursorEventToAgentMessage } from './utils/cursorLegacyEventConverter';
|
||||
import { cursorPassThroughStatusMessage, parseCursorSpecialCommand } from './cursorSpecialCommands';
|
||||
// NOTE: model-error detection (cursorAgentMessageClassifier) is intentionally
|
||||
// NOT wired into the legacy launcher. The hub auto-migrates legacy stream-json
|
||||
// sessions to ACP at resume time via maybeAutoMigrateLegacyCursorSession (PR
|
||||
// #844). The legacy launcher is reached only when migration soft-fails — a
|
||||
// degraded fallback path, not a supported flow. Carrying duplicate
|
||||
// model-error logic here would (a) double the surface for bugs in the
|
||||
// model-error contract, (b) imply legacy is a real path that needs feature
|
||||
// parity, and (c) be dead code in practice. New cursor sessions are ACP from
|
||||
// inception. If you find yourself wanting model-error detection on this
|
||||
// path, fix the migration failure case instead.
|
||||
|
||||
// Transient `agent` failures (auth expiry, rate limits, transient network) come back
|
||||
// as exit code 1 with a recognisable stderr signature. We requeue and retry instead
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
buildModelErrorBridgePrompt,
|
||||
canBridgeModelError,
|
||||
mergeBridgeGateFields,
|
||||
MODEL_ERROR_BRIDGE_HEADER,
|
||||
MAX_LAST_USER_MESSAGE_CHARS,
|
||||
truncateLastUserMessage
|
||||
} from './cursorModelErrorBridge';
|
||||
|
||||
describe('buildModelErrorBridgePrompt', () => {
|
||||
it('wraps the last user message with bridge context', () => {
|
||||
const prompt = buildModelErrorBridgePrompt({
|
||||
kind: 'transport_closed',
|
||||
rawSnippet: 'WritableIterable is closed',
|
||||
lastUserMessage: 'Fix the login bug in auth.ts',
|
||||
priorAssistantClaimsDone: false
|
||||
});
|
||||
|
||||
expect(prompt).toContain(MODEL_ERROR_BRIDGE_HEADER);
|
||||
expect(prompt).toContain('transport_closed: WritableIterable is closed');
|
||||
expect(prompt).toContain('Re-sending your last message below.');
|
||||
expect(prompt).toContain('---');
|
||||
expect(prompt.endsWith('Fix the login bug in auth.ts')).toBe(true);
|
||||
expect(prompt).not.toContain('verify what is actually done');
|
||||
});
|
||||
|
||||
it('adds completion verification when priorAssistantClaimsDone is true', () => {
|
||||
const prompt = buildModelErrorBridgePrompt({
|
||||
kind: 'rpc_timeout',
|
||||
rawSnippet: 'request timed out after 30000ms',
|
||||
lastUserMessage: 'ship the feature',
|
||||
priorAssistantClaimsDone: true
|
||||
});
|
||||
|
||||
expect(prompt).toContain('verify what is actually done before proceeding.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('canBridgeModelError', () => {
|
||||
const base = {
|
||||
transient: true,
|
||||
eventId: 'evt-1000'
|
||||
};
|
||||
|
||||
it('allows transient errors that have not been bridged', () => {
|
||||
expect(canBridgeModelError(base)).toBe(true);
|
||||
});
|
||||
|
||||
it('blocks non-transient errors', () => {
|
||||
expect(canBridgeModelError({ ...base, transient: false })).toBe(false);
|
||||
});
|
||||
|
||||
it('blocks quota and auth style failures via transient=false', () => {
|
||||
expect(canBridgeModelError({
|
||||
...base,
|
||||
transient: false
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('dedupes when this eventId was already bridged', () => {
|
||||
expect(canBridgeModelError({
|
||||
...base,
|
||||
bridgedForEventId: 'evt-1000'
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('allows a new error after a prior bridge on a different eventId', () => {
|
||||
expect(canBridgeModelError({
|
||||
...base,
|
||||
eventId: 'evt-2000',
|
||||
bridgedForEventId: 'evt-1000'
|
||||
})).toBe(true);
|
||||
});
|
||||
|
||||
it('blocks when bridge already failed', () => {
|
||||
expect(canBridgeModelError({
|
||||
...base,
|
||||
retriedAndFailed: true
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('blocks when a newer normal turn superseded the error', () => {
|
||||
expect(canBridgeModelError({
|
||||
...base,
|
||||
supersededByUserTurn: true
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('blocks when bridgeable is explicitly false', () => {
|
||||
expect(canBridgeModelError({
|
||||
...base,
|
||||
bridgeable: false
|
||||
})).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergeBridgeGateFields', () => {
|
||||
it('keeps prior bridgedForEventId when hub snapshot omits it', () => {
|
||||
const merged = mergeBridgeGateFields(
|
||||
{ bridgedForEventId: 'evt-1000', retriedAndFailed: false },
|
||||
{ bridgedForEventId: undefined, retriedAndFailed: false }
|
||||
);
|
||||
expect(merged.bridgedForEventId).toBe('evt-1000');
|
||||
expect(canBridgeModelError({
|
||||
transient: true,
|
||||
eventId: 'evt-1000',
|
||||
...merged
|
||||
})).toBe(false);
|
||||
});
|
||||
|
||||
it('preserves retriedAndFailed when hub sends false', () => {
|
||||
const merged = mergeBridgeGateFields(
|
||||
{ bridgedForEventId: 'evt-1000', retriedAndFailed: true },
|
||||
{ bridgedForEventId: undefined, retriedAndFailed: false }
|
||||
);
|
||||
expect(merged.retriedAndFailed).toBe(true);
|
||||
});
|
||||
|
||||
it('preserves supersededByUserTurn when hub omits it', () => {
|
||||
const merged = mergeBridgeGateFields(
|
||||
{ supersededByUserTurn: true },
|
||||
{ bridgedForEventId: undefined, retriedAndFailed: false, supersededByUserTurn: undefined }
|
||||
);
|
||||
expect(merged.supersededByUserTurn).toBe(true);
|
||||
expect(canBridgeModelError({
|
||||
transient: true,
|
||||
eventId: 'evt-1000',
|
||||
...merged
|
||||
})).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('truncateLastUserMessage', () => {
|
||||
it('passes through short messages unchanged', () => {
|
||||
expect(truncateLastUserMessage('hello')).toBe('hello');
|
||||
});
|
||||
|
||||
it('caps very long messages', () => {
|
||||
const long = 'x'.repeat(40_000);
|
||||
expect(truncateLastUserMessage(long).length).toBe(MAX_LAST_USER_MESSAGE_CHARS);
|
||||
});
|
||||
});
|
||||
|
||||
describe('MAX_LAST_USER_MESSAGE_CHARS', () => {
|
||||
it('is the bridge fail-closed limit', () => {
|
||||
expect(MAX_LAST_USER_MESSAGE_CHARS).toBe(32_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
export const MODEL_ERROR_BRIDGE_HEADER = '[HAPI bridge — transient model error]';
|
||||
|
||||
export const MAX_LAST_USER_MESSAGE_CHARS = 32_000;
|
||||
const MAX_EXCERPT_CHARS = 120;
|
||||
|
||||
export type ModelErrorBridgeInput = {
|
||||
kind: string;
|
||||
rawSnippet: string;
|
||||
lastUserMessage: string;
|
||||
priorAssistantClaimsDone: boolean;
|
||||
};
|
||||
|
||||
export type ModelErrorBridgeGate = {
|
||||
transient: boolean;
|
||||
eventId: string;
|
||||
bridgedForEventId?: string;
|
||||
retriedAndFailed?: boolean;
|
||||
supersededByUserTurn?: boolean;
|
||||
/** Explicit false blocks Bridge (e.g. idle stderr after a successful turn). */
|
||||
bridgeable?: boolean;
|
||||
};
|
||||
|
||||
export function truncateLastUserMessage(message: string): string {
|
||||
if (message.length <= MAX_LAST_USER_MESSAGE_CHARS) {
|
||||
return message;
|
||||
}
|
||||
return message.slice(0, MAX_LAST_USER_MESSAGE_CHARS);
|
||||
}
|
||||
|
||||
export function buildModelErrorBridgePrompt(input: ModelErrorBridgeInput): string {
|
||||
const excerpt = input.rawSnippet
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, MAX_EXCERPT_CHARS);
|
||||
|
||||
const lines = [
|
||||
MODEL_ERROR_BRIDGE_HEADER,
|
||||
'',
|
||||
`The previous turn failed before completing (${input.kind}: ${excerpt}).`,
|
||||
'',
|
||||
'Re-sending your last message below. Continue the task from where you left off.',
|
||||
'Do not repeat work you already finished unless the error invalidated it.'
|
||||
];
|
||||
|
||||
if (input.priorAssistantClaimsDone) {
|
||||
lines.push('');
|
||||
lines.push('You may have reported completion before this error — verify what is actually done before proceeding.');
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
lines.push('---');
|
||||
lines.push(input.lastUserMessage);
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function canBridgeModelError(gate: ModelErrorBridgeGate): boolean {
|
||||
if (!gate.transient) {
|
||||
return false;
|
||||
}
|
||||
if (gate.bridgeable === false) {
|
||||
return false;
|
||||
}
|
||||
if (gate.retriedAndFailed) {
|
||||
return false;
|
||||
}
|
||||
if (gate.supersededByUserTurn) {
|
||||
return false;
|
||||
}
|
||||
if (gate.bridgedForEventId === gate.eventId) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Merge hub RPC snapshot gates into local state without clobbering. */
|
||||
export function mergeBridgeGateFields(
|
||||
prior: Pick<ModelErrorBridgeGate, 'bridgedForEventId' | 'retriedAndFailed' | 'supersededByUserTurn' | 'bridgeable'> | null | undefined,
|
||||
incoming: Pick<ModelErrorBridgeGate, 'bridgedForEventId' | 'retriedAndFailed' | 'supersededByUserTurn' | 'bridgeable'>
|
||||
): Pick<ModelErrorBridgeGate, 'bridgedForEventId' | 'retriedAndFailed' | 'supersededByUserTurn' | 'bridgeable'> {
|
||||
return {
|
||||
bridgedForEventId: incoming.bridgedForEventId ?? prior?.bridgedForEventId,
|
||||
retriedAndFailed: incoming.retriedAndFailed === true || prior?.retriedAndFailed === true,
|
||||
supersededByUserTurn: incoming.supersededByUserTurn === true
|
||||
|| prior?.supersededByUserTurn === true,
|
||||
// false wins — never re-open Bridge from a stale hub omit.
|
||||
bridgeable: incoming.bridgeable === false || prior?.bridgeable === false
|
||||
? false
|
||||
: (incoming.bridgeable ?? prior?.bridgeable)
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
let autoBridgeTransientModelErrors = false;
|
||||
|
||||
export function setAutoBridgeTransientModelErrors(enabled: boolean): void {
|
||||
autoBridgeTransientModelErrors = enabled;
|
||||
}
|
||||
|
||||
export function getAutoBridgeTransientModelErrors(): boolean {
|
||||
return autoBridgeTransientModelErrors;
|
||||
}
|
||||
@@ -7,6 +7,23 @@ import type { EnhancedMode } from './loop';
|
||||
const mode: EnhancedMode = { permissionMode: 'default' };
|
||||
|
||||
describe('enqueueCursorUserMessage', () => {
|
||||
it('preserves caller bridge: localId but keeps the turn non-bridge provenance', async () => {
|
||||
const consumed: string[] = [];
|
||||
const queue = new MessageQueue2<EnhancedMode>((m) => m.permissionMode);
|
||||
queue.onBatchConsumed = (localIds) => {
|
||||
consumed.push(...localIds);
|
||||
};
|
||||
enqueueCursorUserMessage(queue, 'please continue', mode, 'bridge:evt-1');
|
||||
expect(queue.queue).toHaveLength(1);
|
||||
expect(queue.queue[0]?.localId).toBe('bridge:evt-1');
|
||||
expect(queue.queue[0]?.internal).toBeUndefined();
|
||||
expect(queue.hasPendingNonBridgeTurn()).toBe(true);
|
||||
|
||||
const batch = await queue.waitForMessagesAndGetAsString();
|
||||
expect(batch?.items[0]?.internal).toBeUndefined();
|
||||
expect(consumed).toEqual(['bridge:evt-1']);
|
||||
});
|
||||
|
||||
it('isolates /compress from a following same-mode prompt', async () => {
|
||||
const queue = new MessageQueue2<EnhancedMode>((m) => m.permissionMode);
|
||||
enqueueCursorUserMessage(queue, '/compress keep recap', mode, 'a');
|
||||
|
||||
@@ -12,6 +12,9 @@ export function enqueueCursorUserMessage(
|
||||
enhancedMode: EnhancedMode,
|
||||
localId?: string
|
||||
): void {
|
||||
// Preserve caller localId for messages-consumed / cancel. Bridge provenance
|
||||
// is queue-owned (`internal.kind === 'model-error-bridge'`), so a forged
|
||||
// `bridge:*` localId cannot impersonate a Bridge turn.
|
||||
const specialCommand = parseCursorSpecialCommand(formattedText);
|
||||
if (specialCommand.type !== null) {
|
||||
messageQueue.pushIsolated(formattedText.trim(), enhancedMode, localId);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { formatMessageWithAttachments } from '@/utils/attachmentFormatter';
|
||||
import { getInvokedCwd } from '@/utils/invokedCwd';
|
||||
import { enqueueCursorUserMessage } from './cursorUserMessageQueue';
|
||||
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
|
||||
import { setAutoBridgeTransientModelErrors } from './cursorModelErrorBridgePrefs';
|
||||
|
||||
const formatFailureReason = (message: string): string => {
|
||||
const maxLength = 200;
|
||||
@@ -126,16 +127,24 @@ export async function runCursor(opts: {
|
||||
permissionMode?: unknown;
|
||||
model?: unknown;
|
||||
modelReasoningEffort?: unknown;
|
||||
autoBridgeTransientModelErrors?: unknown;
|
||||
};
|
||||
const applied: {
|
||||
permissionMode?: PermissionMode;
|
||||
model?: string | null;
|
||||
autoBridgeTransientModelErrors?: boolean;
|
||||
} = {};
|
||||
|
||||
if (config.modelReasoningEffort !== undefined) {
|
||||
throw new Error('Invalid model reasoning effort');
|
||||
}
|
||||
|
||||
if (config.autoBridgeTransientModelErrors !== undefined) {
|
||||
const enabled = config.autoBridgeTransientModelErrors === true;
|
||||
setAutoBridgeTransientModelErrors(enabled);
|
||||
applied.autoBridgeTransientModelErrors = enabled;
|
||||
}
|
||||
|
||||
const nextPermissionMode = config.permissionMode !== undefined
|
||||
? resolveSessionConfigPermissionMode<PermissionMode>(config.permissionMode, 'cursor')
|
||||
: undefined;
|
||||
|
||||
Reference in New Issue
Block a user