diff --git a/packages/cursor/README.md b/packages/cursor/README.md index f5e6fc3..4b8b070 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -129,7 +129,22 @@ stateless: 60 seconds with no message at all, or 4 minutes with only Cursor's heartbeats (yetone/magpie#2672, where a Run sent some thinking and then nothing, and the reply waited until the agent gave up after 5 minutes). Only time spent waiting on Cursor counts: a retained Run waiting for the -caller's tool results is bounded by the 120 seconds above instead. +caller's tool results is bounded by the 120 seconds above instead. These +errors explicitly say `stream timed out`, so clients such as Pi that classify +streamed errors by their message can apply their bounded retry policy. A timeout +still fails the request; it never turns an incomplete answer into a success. + +The optional Pi SDK regression uses a loopback SSE fixture and synthetic data; +it reads no real credentials and makes no upstream requests. From the repo root, +pass the directory containing an installed `@earendil-works/pi-coding-agent`: + +```sh +node scripts/cursor-pi-retry.integration.mjs /path/to/pi-coding-agent packages/cursor +node scripts/cursor-pi-retry.integration.mjs /path/to/pi-coding-agent packages/cursor exhausted +``` + +It checks recovery, retry-budget exhaustion, and that a completed tool runs only +once while partial output from failed attempts stays out of retry context. Cursor's count of a step's tool calls includes calls the plugin answers itself: a tool the request doesn't have is refused to the model, and Cursor's own diff --git a/packages/cursor/native-e2e.test.mjs b/packages/cursor/native-e2e.test.mjs index fdf6335..953269a 100644 --- a/packages/cursor/native-e2e.test.mjs +++ b/packages/cursor/native-e2e.test.mjs @@ -1874,7 +1874,11 @@ for (const path of ["native", "stateless"]) { const sse = await sseOf(response) expect(Date.now() - started).toBeLessThan(1000) expect(sse).toContain("native planning one") - expect(sse).toContain("Cursor went quiet: no message for 0 s, its last message thinking (try again)") + expect(sse).toContain("Cursor went quiet: no message for 0 s, its last message thinking; stream timed out (try again)") + const errors = sse.split("\n\n").filter((s) => s.startsWith("data: {")).map((s) => JSON.parse(s.slice(6)).error).filter(Boolean) + expect(errors).toHaveLength(1) + expect(errors[0].message).toMatch(piRetries) + expect(errors[0].message).toMatch(magpiePassing) expect(sse).not.toContain("[DONE]") await until(() => a.closedStreams === 1) }) @@ -1889,6 +1893,11 @@ for (const path of ["native", "stateless"]) { const sse = await sseOf(response) const [, beats] = sse.match(/Cursor went quiet: (\d+) heartbeats and nothing else for \d+ s, its last message thinking/) ?? [] expect(Number(beats)).toBeGreaterThan(0) + const errors = sse.split("\n\n").filter((s) => s.startsWith("data: {")).map((s) => JSON.parse(s.slice(6)).error).filter(Boolean) + expect(errors).toHaveLength(1) + expect(errors[0].message).toMatch(piRetries) + expect(errors[0].message).toMatch(magpiePassing) + expect(sse).not.toContain("[DONE]") await until(() => a.closedStreams === 1) }) } @@ -1912,8 +1921,8 @@ for (const path of ["native", "stateless"]) { const chat = initial({ stream: true, messages: [{ role: "user", content: "prompt " + secret }] }) const sse = await sseOf(await a.ask(account, chat, { input })) expect(sse).toMatch(path === "native" - ? /Cursor went quiet: \d+ heartbeats and nothing else for \d+ s, its last message checkpoint #1 of the Run, the first of step 1, after blob request ×2, thinking \(try again\)/ - : /Cursor went quiet: \d+ heartbeats and nothing else for \d+ s, its last message checkpoint #1 of the Run, after blob request ×2, thinking \(try again\)/) + ? /Cursor went quiet: \d+ heartbeats and nothing else for \d+ s, its last message checkpoint #1 of the Run, the first of step 1, after blob request ×2, thinking; stream timed out \(try again\)/ + : /Cursor went quiet: \d+ heartbeats and nothing else for \d+ s, its last message checkpoint #1 of the Run, after blob request ×2, thinking; stream timed out \(try again\)/) await until(() => a.closedStreams === 1) const files = readdirSync(join(dir, "cursor-traces")) expect(files).toHaveLength(1) diff --git a/packages/cursor/native-session.mjs b/packages/cursor/native-session.mjs index eee34c6..5cfdfe6 100644 --- a/packages/cursor/native-session.mjs +++ b/packages/cursor/native-session.mjs @@ -133,7 +133,8 @@ export class Quiet { fire() { const gap = Date.now() - this.since const what = this.heard + gap >= this.limits.quiet ? `${this.heartbeats} heartbeats and nothing else for ${Math.round((this.heard + gap) / 1000)} s` : `no message for ${Math.round(gap / 1000)} s` - this.why = `Cursor went quiet: ${what}${this.last ? ", its last message " + this.lastSaid() : ""} (try again)` + // Pi classifies streamed errors by message after the HTTP status is lost. + this.why = `Cursor went quiet: ${what}${this.last ? ", its last message " + this.lastSaid() : ""}; stream timed out (try again)` this.trace?.event("quiet", { heard: this.heard + gap, heartbeats: this.heartbeats }) this.gone?.() this.stop({ status: 502, message: this.why }) diff --git a/packages/cursor/native-session.test.mjs b/packages/cursor/native-session.test.mjs index ca04a19..6ccd729 100644 --- a/packages/cursor/native-session.test.mjs +++ b/packages/cursor/native-session.test.mjs @@ -430,7 +430,7 @@ test("native protocol: a step silent after its first call fails at idle, before await new Promise(() => {}) })()) await until(() => run.error) - expect(run.error).toMatchObject({ status: 502, message: "Cursor went quiet: no message for 0 s, its last message tool call (try again)" }) + expect(run.error).toMatchObject({ status: 502, message: "Cursor went quiet: no message for 0 s, its last message tool call; stream timed out (try again)" }) expect(Date.now() - started).toBeLessThan(1000) }) @@ -472,7 +472,7 @@ test("native protocol: a quiet Run's error says its checkpoint was a repeat, its await new Promise(() => {}) })()) await until(() => run.error) - expect(run.error.message).toBe("Cursor went quiet: no message for 0 s, its last message checkpoint #2 of the Run, number 2 of step 1, 2 in a row, after thinking ×2, text (try again)") + expect(run.error.message).toBe("Cursor went quiet: no message for 0 s, its last message checkpoint #2 of the Run, number 2 of step 1, 2 in a row, after thinking ×2, text; stream timed out (try again)") }) test("native protocol: a checkpoint after the caller's results is the first of the next step (plugins#550)", async () => { @@ -485,7 +485,7 @@ test("native protocol: a checkpoint after the caller's results is the first of t await new Promise(() => {}) })()) await until(() => run.error) - expect(run.error.message).toBe("Cursor went quiet: no message for 0 s, its last message checkpoint #4 of the Run, the first of step 2, after nothing else (try again)") + expect(run.error.message).toBe("Cursor went quiet: no message for 0 s, its last message checkpoint #4 of the Run, the first of step 2, after nothing else; stream timed out (try again)") }) test("native protocol: Wire trace writes a failed Run, never a cancelled one, and only while on (plugins#550)", async () => { diff --git a/packages/cursor/package.json b/packages/cursor/package.json index d5b771d..13597a4 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.45", + "version": "0.2.46", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./opencode.mjs", diff --git a/scripts/cursor-pi-retry.integration.mjs b/scripts/cursor-pi-retry.integration.mjs new file mode 100644 index 0000000..6294363 --- /dev/null +++ b/scripts/cursor-pi-retry.integration.mjs @@ -0,0 +1,141 @@ +// Run against an installed Pi SDK; all model traffic stays on a loopback fixture. +// node scripts/cursor-pi-retry.integration.mjs packages/cursor [exhausted] +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +const [, , sdkRoot, pluginRoot, mode] = process.argv +if (!sdkRoot || !pluginRoot) throw new Error('Pass the Pi SDK root and Cursor package directory') +const exhausted = mode === 'exhausted' +const { createAgentSession, createExtensionRuntime, ModelRuntime, SessionManager, SettingsManager } = + await import(pathToFileURL(resolve(sdkRoot, 'dist/index.js'))) +const { Quiet, NATIVE_LIMITS } = await import(pathToFileURL(resolve(pluginRoot, 'native-session.mjs'))) +const quiet = new Quiet(NATIVE_LIMITS, () => {}) +quiet.since = Date.now() - 60_000 +quiet.last = 'blob request' +quiet.fire() +const errorMessage = quiet.why +const tmp = mkdtempSync(join(tmpdir(), 'cursor-pi-retry-')) +const requests = [] +let executions = 0 +const server = createServer(async (req, res) => { + let body = '' + for await (const part of req) body += part + try { + requests.push(JSON.parse(body)) + } catch { + res.writeHead(400) + res.end('Invalid fixture request JSON') + return + } + res.writeHead(200, { 'Content-Type': 'text/event-stream' }) + const send = (data) => res.write('data: ' + JSON.stringify(data) + '\n\n') + const chunk = (delta, finish_reason = null) => send({ + id: 'synthetic-' + requests.length, + object: 'chat.completion.chunk', + created: 1, + model: 'fixture', + choices: [{ index: 0, delta, finish_reason }], + }) + chunk({ role: 'assistant' }) + if (requests.length === 1) { + chunk({ tool_calls: [{ + index: 0, id: 'call_once', type: 'function', + function: { name: 'diagnostic_once', arguments: '{}' }, + }] }) + chunk({}, 'tool_calls') + res.end('data: [DONE]\n\n') + } else if (requests.length === 2 || exhausted) { + chunk({ content: 'INCOMPLETE_DRAFT_SHOULD_BE_OMITTED' }) + send({ error: { status: 502, message: errorMessage } }) + res.end() + } else { + chunk({ content: 'RECOVERED' }) + chunk({}, 'stop') + res.end('data: [DONE]\n\n') + } +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +const baseUrl = `http://127.0.0.1:${server.address().port}/v1` +writeFileSync(join(tmp, 'models.json'), JSON.stringify({ providers: { fixture: { + api: 'openai-completions', baseUrl, apiKey: 'synthetic', + models: [{ + id: 'fixture', name: 'fixture', reasoning: false, input: ['text'], + contextWindow: 32000, maxTokens: 1024, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, + }], +} } })) +const modelRuntime = await ModelRuntime.create({ + authPath: join(tmp, 'auth.json'), modelsPath: join(tmp, 'models.json'), +}) +const resourceLoader = { + getExtensions: () => ({ extensions: [], errors: [], runtime: createExtensionRuntime() }), + getSkills: () => ({ skills: [], diagnostics: [] }), + getPrompts: () => ({ prompts: [], diagnostics: [] }), + getThemes: () => ({ themes: [], diagnostics: [] }), + getAgentsFiles: () => ({ agentsFiles: [] }), + getSystemPrompt: () => 'Synthetic retry integration test.', + getSystemPromptSource: () => undefined, + getAppendSystemPrompt: () => [], + getAppendSystemPromptSources: () => [], + extendResources: () => {}, + reload: async () => {}, +} +let session +try { + ;({ session } = await createAgentSession({ + cwd: tmp, agentDir: tmp, modelRuntime, + model: modelRuntime.getModel('fixture', 'fixture'), thinkingLevel: 'off', + resourceLoader, sessionManager: SessionManager.inMemory(tmp), + settingsManager: SettingsManager.inMemory({ + compaction: { enabled: false }, + retry: { enabled: true, maxRetries: 2, baseDelayMs: 1, maxAgentDelayMs: 1 }, + }), + tools: ['diagnostic_once'], + customTools: [{ + name: 'diagnostic_once', label: 'Diagnostic', description: 'Synthetic effect counter', + parameters: { type: 'object', properties: {} }, + execute: async () => { + executions++ + return { content: [{ type: 'text', text: 'ALREADY_EXECUTED_ONCE' }], details: {} } + }, + }], + })) + const retries = [] + session.subscribe((event) => { + if (event.type === 'auto_retry_start' || event.type === 'auto_retry_end') { + retries.push({ type: event.type, success: event.success, attempt: event.attempt }) + } + }) + await session.prompt('Call diagnostic_once, then finish.') + const result = { + requests: requests.length, executions, answer: session.getLastAssistantText(), retries, errorMessage, + } + console.log(JSON.stringify(result, null, 2)) + assert.equal(requests.length, exhausted ? 4 : 3, 'Retry count must follow the configured budget') + assert.equal(executions, 1, 'A completed tool must not execute again') + for (const request of requests.slice(2)) { + const history = JSON.stringify(request.messages) + assert.equal(history.includes('INCOMPLETE_DRAFT_SHOULD_BE_OMITTED'), false, + 'Failed partial output must be omitted from retry context') + assert.equal(history.includes('ALREADY_EXECUTED_ONCE'), true, + 'Completed tool result must remain in retry context') + } + if (exhausted) { + assert.equal(session.messages.at(-1).stopReason, 'error') + assert.equal(retries.filter((event) => event.type === 'auto_retry_start').length, 2) + assert.equal(retries.at(-1).success, false) + } else { + assert.equal(result.answer, 'RECOVERED') + assert.equal(retries.at(-1).success, true) + } + console.log(`PASS: real Pi SDK ${exhausted ? 'exhausts its bounded retry budget' : 'recovers after a Cursor timeout'} without repeating the tool.`) +} finally { + session?.dispose() + server.closeAllConnections() + await new Promise((resolve) => server.close(resolve)) + rmSync(tmp, { recursive: true, force: true }) +}