diff --git a/packages/cursor/README.md b/packages/cursor/README.md index f1951d0..ea6c4be 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -101,9 +101,12 @@ Tool results can continue a retained Run in the same plugin process. The owner uses the same session/cache key and first user message as `conversation_id`, so Task subagents sharing their parent's session can run independently. Retention waits at most 120 seconds for a result batch and 15 minutes for a Run's total -lifetime. A continuation arriving in the last minute of that lifetime rebuilds -from supplied history before submitting results to the old Run. The absolute -deadline still applies to an active segment; it is never extended by activity. +lifetime. A continuation arriving with less than 10 minutes of that lifetime +left rebuilds from supplied history on a fresh Run before submitting results +to the old one, since one step can be a long answer. The absolute deadline +still applies to an active segment; it is never extended by activity. A Run +cut by it mid-answer ends with `native Run lifetime expired: the Run timed +out; retry your request`, words agents ask again on. The pool holds at most 8 owners per account and 32 per process, with bounded history, blobs, arguments, and pending writes. When pending writes reach their bound (a long history asks for its blobs at once, and a slow link diff --git a/packages/cursor/native-e2e.test.mjs b/packages/cursor/native-e2e.test.mjs index 28c0461..e05d4ee 100644 --- a/packages/cursor/native-e2e.test.mjs +++ b/packages/cursor/native-e2e.test.mjs @@ -166,6 +166,8 @@ async function agent(options = {}) { marker = options.finalAfterFirst ? received.get(firstID).content[0].text : options.parallel ? [7, 8].map((id) => received.get(id).content[0].text).join("|") : received.get(8).content[0].text phase = 2 if (options.stallFinal) return + // the answer begun and still going when the Run's deadline lands + if (options.halfFinal) { send(update(1, text(1, "half said"))); return } send(update(4, text(1, "native final thinking"))) send(update(1, text(1, marker))) const usage = options.turnUsage ?? (options.zeroUsage ? message(uint(1, 0), uint(2, 0), uint(5, 0)) : message(uint(1, 23), uint(2, 7), uint(3, 10), uint(4, 0), uint(5, 4))) @@ -358,6 +360,75 @@ test("native retention: a near-expiry Run rebuilds before submitting results or } finally { clock.mockRestore() } }) +// plugins#616 (yetone/magpie#4419, Okxdd123; ggbdpq's cause and repro): a +// Pi turn's 13th tool step went on in its retained Run with 494 s of the +// 15-minute lifetime left, and the answer was still streaming when the +// deadline cut it. A step with less than continueReserve left starts on a +// fresh Run instead; one with more still goes on in the same Run. The +// clock is moved, nothing waits. +for (const [left, fresh] of [[494_000, true], [NATIVE_LIMITS.continueReserve - 1000, true], [NATIVE_LIMITS.continueReserve + 60_000, false]]) test(`native retention: a continuation with ${left / 1000}s of the lifetime left ${fresh ? "rebuilds on a fresh Run" : "goes on in the same Run"} (#616)`, async () => { + const a = await agent(), account = auth(), chat = initial() + const first = await a.ask(account, chat) + expect(first.status).toBe(200) + const owner = [...nativeSessions.entries][0] + const now = Date.now.bind(Date) + const shift = owner.expiresAt - now() - left + const clock = spyOn(Date, "now").mockImplementation(() => now() + shift) + try { + const marker = "step-with-" + left + const next = await a.ask(account, continueWith(chat, first.body, [marker])) + if (fresh) { + rebuilt(next, marker) + expect(a.runs).toHaveLength(2) + expect(a.results).toEqual([]) + expect(owner.state).toBe("expired") + } else { + expect(next.status).toBe(200) + expect(next.diagnostic).toMatch(/^same-run/) + expect(a.runs).toHaveLength(1) + expect(a.results).toHaveLength(1) + } + expect(a.errors).toEqual([]) + } finally { clock.mockRestore() } +}) + +// When the deadline still lands mid-answer, the 200 is long sent and the +// agent reads only the error's words: they must be ones it asks again on. +// Pi judges by the text alone (its _isRetryableError), as magpie's +// passingSaid does for a stream error; both regexes are copied here. +const piRetries = /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|http2 request did not get a response|timed? out|timeout|terminated|retry delay/i +const magpiePassing = /\b(429|500|502|503|504)\b|timed? ?out|rate.?limit|too many requests|overloaded|service.?unavailable|server.?error|internal.?error|connection.?(error|refused|reset)|retry your request|try your request again/i +test("native retention: a Run cut at its deadline mid-answer says to retry the request (#616)", async () => { + const a = await agent({ finalAfterFirst: true, halfFinal: true }), account = auth(), chat = initial() + const first = await a.ask(account, chat) + expect(first.status).toBe(200) + const owner = [...nativeSessions.entries][0] + const res = await a.ask(account, { ...continueWith(chat, first.body, ["after the tool"]), stream: true }) + expect(res.status).toBe(200) + const reader = res.body.getReader(), dec = new TextDecoder() + let sse = "" + while (!sse.includes("half said")) { + const { value, done } = await reader.read() + if (done) break + sse += dec.decode(value, { stream: true }) + } + expect(sse).toContain("half said") + // the deadline brought in to now: the answer is still going + owner.expireIn(0) + for (;;) { + const { value, done } = await reader.read() + if (done) break + sse += dec.decode(value, { stream: true }) + } + 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).toStartWith("native Run lifetime expired") + expect(errors[0].message).toMatch(piRetries) + expect(errors[0].message).toMatch(magpiePassing) + expect(errors[0].message).toContain("retry your request") + expect(owner.state).toBe("expired") +}) + for (const limit of ["resultWait", "lifetime"]) test(`native retention: ${limit} expiry rebuilds supplied results on a fresh stateless Run`, async () => { // #143: the lifetime counts from the Run's start, so a short one set before // the first ask expired a first Run slower than it on a loaded machine. diff --git a/packages/cursor/native-session.mjs b/packages/cursor/native-session.mjs index af6e46f..00681d2 100644 --- a/packages/cursor/native-session.mjs +++ b/packages/cursor/native-session.mjs @@ -8,6 +8,13 @@ import { join } from "node:path" export const NATIVE_LIMITS = { resultWait: 120_000, lifetime: 15 * 60_000, + // How much of the lifetime a retained Run must have left to take a tool + // batch's results and go on; with less, the step starts on a fresh Run + // from the supplied history. One step can be a long answer: a Pi turn on + // grok-4.7 went on with 494 s left and was still answering at the + // deadline (plugins#616, yetone/magpie#4419). At most two thirds of the + // lifetime, so a short one set in a test still has room to continue. + continueReserve: 10 * 60_000, batchWait: 30_000, // How long a stateless step whose calls came waits for Cursor's count of // them (update 27) with nothing but heartbeats before it hands the calls @@ -728,6 +735,13 @@ class Segment { } } +// What a Run cut at its absolute deadline says. It most often lands +// mid-answer, the 200 long sent, so the agent reads only these words; the +// conversation is not lost (asked again, the history goes on a fresh Run), +// and they say so in words agents retry on: "timed out" (Pi, magpie's +// passingSaid) and "retry your request" (plugins#616, yetone/magpie#4419). +export const LIFETIME_EXPIRED = "native Run lifetime expired: the Run timed out; retry your request" + export class NativeSessionPool { constructor(limits = NATIVE_LIMITS) { this.limits = limits @@ -769,7 +783,7 @@ export class NativeSessionPool { // A retained Run's absolute timer spans all tool roundtrips. Rebuild // near its deadline before writing this batch: otherwise a new Chat // segment can lose its transport after already exposing output. - const reserve = Math.min(60_000, owner.limits.lifetime / 10) + const reserve = Math.min(owner.limits.continueReserve, owner.limits.lifetime * 2 / 3) if (owner.expiresAt - Date.now() <= reserve) { owner.fail({ status: 410, message: "native Run retired before lifetime deadline" }, "expired") return fallback("owner near lifetime deadline") @@ -867,7 +881,7 @@ class NativeSession { expireIn(ms) { clearTimeout(this.lifetimeTimer) this.expiresAt = Date.now() + ms - this.lifetimeTimer = later(() => this.fail({ status: 410, message: "native Run lifetime expired" }, "expired"), ms) + this.lifetimeTimer = later(() => this.fail({ status: 410, message: LIFETIME_EXPIRED }, "expired"), ms) } retain(n) { if (this.retainedBytes + n > this.limits.outputBytes) invalid("native output/history retention limit reached", 503) diff --git a/packages/cursor/package.json b/packages/cursor/package.json index be05939..0b121cd 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-cursor-auth", - "version": "0.2.36", + "version": "0.2.37", "description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to", "type": "module", "main": "./index.mjs",