cursor 0.2.35: a step ends on calls Cursor completed itself, or on a checkpoint waiting on every call (#550)

Windsland52's wire trace (stateless path): partial c1 -> completed c1,
partial c2 -> completed c2, partial c3 -> started c3 -> one exec, then
the tool count (update 27), 7 set_blob, a checkpoint whose
pending_tool_calls (ConversationStateStructure 4) holds one id, and
240s of heartbeats. Cursor's count includes calls it completed itself
(#7 then #3, with no #2 and no exec), which never reach this side, so
the step waited for calls that were never coming while Cursor waited on
the one exec's result. The native path had the same gap and failed after
batchWait. Cursor's own client (cursor-agent 2026.10.01) takes a
toolCallCompleted for a call it never started, and never waits on
toolRequestsListed.

Now, on both paths, a #3 for a call seen as #7 in the same step, never
started (#2) or exec'd here, counts toward the step's tool count, and a
checkpoint after the count whose pending calls equal the calls this side
holds ends the step too. The strict "more calls than the count" check
still counts only calls that came and were answered here. The quiet
error and batchWait name the count, the calls, the answered and those
completed by Cursor; the Wire trace keeps each update's count, tool
kind, pending and why the Run was cut. Update 8 is named (token count).

Run at this head: stall-550.test.mjs (10 tests, built from the trace's
195 inbound frames in order) and the cursor suite 376/0 on mote; the
root suite with a temp HOME 4196 pass, 0 fail, and check.mjs cursor ok
on mote; native-session, native-e2e, stall-550, conversation and
stepusage 191/0 on Windows (win-run).
Broken by hand, each red only in its own test: the stateless
completed-by-Cursor rule, the stateless checkpoint rule, the native
completed rule, the native checkpoint (waitedOn), and the #7-in-this-step
requirement.
Not tried: a real Cursor account; the real count value (the trace gives
only 2..127); that a #3's call_id equals McpArgs.tool_call_id; what the
two completed calls were; whether Cursor can checkpoint mid-step with
pending equal to the calls before more execs.
This commit is contained in:
yetone
2026-10-31 16:36:38 +08:00
parent 1a5b184991
commit b70725c1a6
5 changed files with 382 additions and 16 deletions
+9 -3
View File
@@ -123,8 +123,11 @@ caller's tool results is bounded by the 120 seconds above instead.
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
`get_mcp_tools` is answered with the request's tools. The step's calls are the
rest.
`get_mcp_tools` is answered with the request's tools. It also includes calls
Cursor completes by itself, which it writes and completes in the step but never
starts on the client or sends to it; those count toward it too. Once the count
has come, a checkpoint whose state waits on exactly the calls the caller was
given also ends the step (#550). The step's calls are the rest.
These are retention limits. A missing, expired, restarted, busy, incompatible,
or full owner uses the original history reconstruction and stateless decoder
@@ -312,7 +315,10 @@ portable data folder. The newest 20 are kept. A file holds the Run's
frames in order, both ways, as each frame's time (ms from the Run's
start), size, kind (text, thinking, checkpoint, heartbeat, ...), field
numbers and sizes, and the field numbers and sizes one level inside them,
plus the error and the model id. No prompt, reply or thinking text, tool
plus the error and the model id. A few of Cursor's numbers are kept too: a
tool count's value, which kind of call (the field number of Cursor's tool
call) a call update is about, how many calls a checkpoint waits on, and,
for a Run that went without the native session, why. No prompt, reply or thinking text, tool
name or argument, blob or checkpoint content, token, header, account or
conversation id is written; the error's message has anything shaped like
an email, id or token taken out. Look the file over before you attach it.
+41 -9
View File
@@ -28,7 +28,7 @@
//
// OpenCode speaks chat completions to it (@ai-sdk/openai-compatible); the
// fetch here answers them.
import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs, Quiet, setWireTrace } from "./native-session.mjs"
import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs, pendingCalls, Quiet, setWireTrace, StepCalls } from "./native-session.mjs"
import { isDeepStrictEqual } from "node:util"
import http2 from "node:http2"
import { STATUS_CODES } from "node:http"
@@ -2747,7 +2747,7 @@ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode,
// runOnce is one Run of the chat on the agent API at base: an async
// iterator of the answer's pieces, or the error it failed with before any.
async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params }) {
async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params, why }) {
// the Run's conversation_id, a new one when nothing names the session:
// its usage event is found by it
const cid = convID || randomUUID()
@@ -2778,7 +2778,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
let closed = false
let heartbeat
// a Run Cursor stops answering ends, as a retained one does (#2672)
const quiet = new Quiet(NATIVE_LIMITS, () => close(), { path: "stateless", model: id })
const quiet = new Quiet(NATIVE_LIMITS, () => close(), { path: "stateless", model: id, why })
const send = (msg) => {
if (!closed && !req.destroyed && req.writable) {
quiet.trace?.frame("out", msg)
@@ -2822,6 +2822,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
close,
stepUsage: book.own,
owedUsage: book.owed,
note: (name) => quiet.trace?.event(name),
})
const wrapped = (async function* () {
try {
@@ -2852,7 +2853,7 @@ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, pa
// decode follows the server's messages into the answer's pieces until the
// turn ends, or the model has made its tool calls.
async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, owedUsage }) {
async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage, owedUsage, note }) {
let calls = 0
// answered: the step's calls answered here (a refusal, the MCP tool
// list), which Cursor's count of the step's calls takes in too (#142)
@@ -2860,14 +2861,18 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
// ended: Cursor said what the turn used
let ended = false
let listed = 0
// what Cursor said of the step's calls: those it completed by itself
// count toward listed too, and never come as an exec (plugins#550)
const step = new StepCalls(fields)
// stepDone is whether every call the step listed has come. A step whose
// calls were all answered here goes on on Cursor's side, under a count of
// its own.
const stepDone = () => {
if (!listed || calls + answered < listed) return false
if (!listed || calls + answered + step.completed < listed) return false
if (calls > 0) return true
listed = 0
answered = 0
step.nextStep()
return false
}
let said = 0
@@ -2984,6 +2989,16 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
return
}
break
case 2: // a call started on the client
case 3: // a call completed: by Cursor itself when it never started here
case 7: // a call the model is writing
// still named in an empty reply's list: only their ids are read
count(seen.updates, u.num)
if (step.update(u.num, uf) && (note?.("completed by Cursor"), stepDone())) {
yield await settled()
return
}
break
default:
count(seen.updates, u.num)
}
@@ -2991,6 +3006,7 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
break
case 2: {
// exec_server_message: the server asks the client to run something
step.exec(m.data)
const call = exec(m.data, tools, send, closeExec, seen.refused)
if (call) {
said += call.args.length
@@ -3003,6 +3019,18 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
}
break
}
case 3:
// conversation_checkpoint_update: Cursor's state. Once the step
// has its count, a state waiting on just the calls handed to the
// caller is a step Cursor has finished: what more the count
// says will not come (plugins#550)
if (listed && calls > 0 && pendingCalls(m.data, fields) === calls) {
note?.("waited on")
yield await settled()
return
}
count(seen.messages, m.num)
break
case 4: {
// kv_server_message: a blob wanted, or one to keep
const kv = fields(m.data)
@@ -3033,7 +3061,10 @@ async function* decode(stream, { send, blobs, tools, estimate, close, stepUsage,
} catch (e) {
// gone quiet is no answer, calls or not: the step's count never came
if (e?.quiet) {
yield { error: { status: e.status, message: e.message } }
// with what came of the step's calls, as the native path's batch
// error says it (plugins#550)
const batch = calls || listed ? `; the step's tool count ${listed || "not sent"}: ${calls} calls came, ${answered} answered here, ${step.completed} completed by Cursor` : ""
yield { error: { status: e.status, message: batch ? e.message.replace(/( \(try again\))?$/, batch + "$1") : e.message } }
return
}
if (calls > 0 && /EOF/.test(e?.message ?? "")) {
@@ -3207,10 +3238,11 @@ async function answerOf(auth, chat, signal, session = "") {
// uses the original history builder/decoder without cancelling a live parent.
const native = prepared.fallback ? null : nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure })
const args = { tok, base, id, tools, conv, convID, signal, maxMode, params }
let response = native ? await runNative({ ...args, native }) : await runOnce(args)
let response = native ? await runNative({ ...args, native }) : await runOnce({ ...args, why: prepared.fallback || "retention capacity or reservation unavailable" })
const rebuild = async () => {
const fallback = await runOnce(args)
fallback.diagnostic = "stateless; bootstrap=imported-history; reason=" + (response.error?.continuityReason || "missing-batch-count")
const why = response.error?.continuityReason || "missing-batch-count"
const fallback = await runOnce({ ...args, why })
fallback.diagnostic = "stateless; bootstrap=imported-history; reason=" + why
return fallback
}
// A missing or conflicting native batch count may be retried once,
+119 -3
View File
@@ -55,7 +55,13 @@ const failureOf = (e) => ({ status: e?.status ?? 502, message: e?.message ?? Str
// kindOf is what a frame of AgentServerMessage is, for Quiet: a heartbeat
// alone, or what an error names as the last thing Cursor sent
const UPDATES = { 1: "text", 4: "thinking", 14: "turn end", 27: "tool count" }
// (names after cursor-agent's agent.v1 InteractionUpdate, 2026.10.01)
const UPDATES = {
1: "text", 2: "tool call started", 3: "tool call completed", 4: "thinking", 5: "thinking done",
6: "user message", 7: "partial tool call", 8: "token count", 9: "summary", 10: "summary started",
11: "summary done", 12: "shell output", 14: "turn end", 15: "tool call delta", 16: "step started",
17: "step done", 27: "tool count",
}
const MESSAGES = { 2: "tool call", 3: "checkpoint", 4: "blob request" }
function kindOf(f) {
if (f.end) return "stream end"
@@ -249,6 +255,26 @@ export function scrub(s) {
.replace(/[A-Za-z0-9_\-+/=.]{24,}/g, "<redacted>")
.slice(0, 2000)
}
// detail is what a trace keeps of an inbound frame past its shape, all of
// it numbers of Cursor's protocol, never content (plugins#550): a tool
// count's number, the kind of call (ToolCall's field) a call update is
// of, and how many calls a checkpoint's state waits on
function detail(data) {
const out = {}
for (const m of nativeFields(data)) {
if (m.num === 1) {
for (const u of nativeFields(m.data)) {
if (u.num === 27) out.count = num(nativeFields(u.data), 1)
else if (u.num === 2 || u.num === 3 || u.num === 7) {
const tc = field(nativeFields(u.data), 2)
const kind = tc && nativeFields(tc.data)[0]
if (kind) out.tool = kind.wire === 2 ? [kind.num, nativeFields(kind.data)[0]?.num ?? 0] : [kind.num]
}
}
} else if (m.num === 3) out.pending = pendingCalls(m.data)
}
return out
}
export class WireTrace {
static open(meta) {
let dir = ""
@@ -258,6 +284,8 @@ export class WireTrace {
constructor(dir, meta = {}) {
this.dir = dir
this.meta = { path: String(meta.path ?? ""), model: String(meta.model ?? "") }
// why a Run went stateless: the retention fallback's reason
if (meta.why) this.meta.why = String(meta.why)
this.started = Date.now()
this.head = []
this.tail = []
@@ -281,6 +309,7 @@ export class WireTrace {
if (dir === "in") entry.kind = kind ?? "heartbeat"
if (dir === "in" && f.end) entry.end = true
else try { entry.fields = shape(data, true) } catch { entry.malformed = true }
if (dir === "in" && !f.end) try { Object.assign(entry, detail(data)) } catch {}
this.push(entry)
}
event(name, extra = {}) {
@@ -438,6 +467,67 @@ const field = (fs, n) => fs.find((f) => f.num === n)
const str = (fs, n) => field(fs, n)?.data.toString("utf8") ?? ""
const num = (fs, n) => field(fs, n)?.n ?? 0
// StepCalls is what Cursor says of a step's calls besides its execs
// (plugins#550). InteractionUpdate 2 (tool_call_started), 3
// (tool_call_completed) and 7 (partial_tool_call) each carry the call's
// call_id (field 1). A call Cursor completed by itself, never started on
// the client and never sent as an exec, is in tool_requests_listed's count
// all the same, and no exec of it will come: 0.2.34 waited for it while
// Cursor waited for the one call it had sent, 240 s, heartbeats only.
// parse is the path's field reader.
export class StepCalls {
constructor(parse) {
this.parse = parse
this.started = new Set()
this.execs = new Set() // the short strings of each exec's args: its tool_call_id among them
this.partial = new Set() // calls the model is writing in this step
this.byCursor = new Set()
}
// update takes an InteractionUpdate's own field (num) and its fields; it
// says whether a call was completed by Cursor: one this step wrote (7)
// and completed (3) with no start on the client (2) and no exec. A
// completion of an earlier step's call is never counted again.
update(n, uf) {
if (n !== 2 && n !== 3 && n !== 7) return false
const id = str(uf, 1)
if (!id) return false
if (n === 2) this.started.add(id)
if (n === 7) this.partial.add(id)
if (n !== 3) return false
if (!this.partial.has(id) || this.started.has(id) || this.execs.has(id) || this.byCursor.has(id)) return false
this.byCursor.add(id)
return true
}
// exec notes an exec's args, whatever its kind: each kind keeps its
// tool_call_id at a field of its own (ShellArgs 4, ReadArgs 2, McpArgs 3)
exec(data) {
try {
for (const e of this.parse(data)) {
if (e.wire !== 2 || e.num === 15 || e.num === 19) continue
for (const a of this.parse(e.data)) if (a.wire === 2 && a.data.length && a.data.length <= 512) this.execs.add(a.data.toString("utf8"))
}
} catch {}
}
get completed() {
return this.byCursor.size
}
// nextStep starts the next step's count
nextStep() {
this.partial.clear()
this.byCursor.clear()
}
}
// pendingCalls is how many calls a checkpoint (ConversationStateStructure)
// says Cursor waits on: its pending_tool_calls, field 4; null when it
// can't be read
export function pendingCalls(data, parse = nativeFields) {
try {
return parse(data).filter((f) => f.num === 4).length
} catch {
return null
}
}
function argsOf(s) {
try {
const v = typeof s === "string" ? JSON.parse(s) : s
@@ -737,6 +827,8 @@ class NativeSession {
this.ac = new AbortController()
this.execs = new Map()
this.nativeCalls = new Map()
// what Cursor said of the step's calls besides its execs (plugins#550)
this.stepCalls = new StepCalls(nativeFields)
this.blobs = new Map()
this.knownHashes = new Set()
this.blobSize = 0
@@ -934,6 +1026,7 @@ class NativeSession {
// caller's results, or after a step whose calls were all answered here.
nextStep(estimate) {
this.steps++
this.stepCalls.nextStep()
this.quiet.nextStep(this.steps)
this.stepSaid = this.said
if (estimate != null) this.stepEstimate = estimate
@@ -951,7 +1044,7 @@ class NativeSession {
this.batchTimer = later(() => {
const s = this.segment
if (s.expected == null && s.calls.length && !this.resultSubmitted) this.missingCount()
else this.fail({ status: 502, message: `Cursor did not complete its declared native tool batch: ${s.calls.length} of ${s.expected ?? "?"} calls came, ${s.answered} answered here, none since ${Date.now() - since} ms` })
else this.fail({ status: 502, message: `Cursor did not complete its declared native tool batch: ${s.calls.length} of ${s.expected ?? "?"} calls came, ${s.answered} answered here${this.stepCalls.completed ? `, ${this.stepCalls.completed} completed by Cursor` : ""}, none since ${Date.now() - since} ms` })
}, this.limits.batchWait)
}
missingCount() {
@@ -967,6 +1060,23 @@ class NativeSession {
if (this.batchTimer) this.waitForBatch()
this.sealBatch()
}
// A call of the step Cursor completed by itself (plugins#550): in its
// count, and never sent as an exec.
completedByCursor() {
if (this.terminal || this.state === "awaiting-results") return
if (this.batchTimer) this.waitForBatch()
this.sealBatch()
}
// A checkpoint whose state waits on just the calls handed to the caller,
// after the step's count, is a step Cursor has finished: what more the
// count says will not come (plugins#550).
waitedOn(data) {
const s = this.segment
if (this.terminal || this.state === "awaiting-results" || s.closed || s.expected == null || !s.calls.length) return
if (pendingCalls(data) !== s.calls.length) return
s.waitedOn = true
this.sealBatch()
}
listed(count) {
if (!Number.isSafeInteger(count) || count < 1) invalid("invalid native tool count", 502)
if (this.segment.expected != null && this.segment.expected !== count) {
@@ -986,7 +1096,8 @@ class NativeSession {
if (segment.expected == null) return
const made = segment.calls.length + segment.answered
if (made > segment.expected) invalid("native tool batch exceeded its declared count", 502)
if (made !== segment.expected || segment.closed) return
// the calls Cursor completed by itself make up the rest (plugins#550)
if ((made + this.stepCalls.completed < segment.expected && !segment.waitedOn) || segment.closed) return
if (!segment.calls.length) {
// Every call of the step was answered here: Cursor goes on with the
// turn by itself, and its next step lists a count of its own.
@@ -1183,10 +1294,14 @@ class NativeSession {
if (this.error) return
} else if (u.num === 13) {
if (this.batchTimer && !this.terminal && this.state !== "awaiting-results") this.waitForBatch()
} else if ((u.num === 2 || u.num === 3 || u.num === 7) && this.stepCalls.update(u.num, uf)) {
this.completedByCursor()
if (this.error) return
}
}
break
case 2: {
this.stepCalls.exec(m.data)
const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id), null, true)
if (c) this.acceptCall(c)
// request_context is Cursor asking for the environment, not a call
@@ -1195,6 +1310,7 @@ class NativeSession {
}
case 3:
this.checkpointReceived(m.data)
this.waitedOn(m.data)
break
case 4: {
const kv = nativeFields(m.data)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-cursor-auth",
"version": "0.2.34",
"version": "0.2.35",
"description": "Cursor subscriptions (Pro, Pro+, Ultra, Teams) in OpenCode and magpie, through the API cursor-agent talks to",
"type": "module",
"main": "./index.mjs",
+212
View File
@@ -0,0 +1,212 @@
// plugins#550 (Windsland52, cursor-grok-4.6-xhigh, stateless path): after
// the step's one exec and its tool count, Cursor saved its blobs and a
// checkpoint and then sent only heartbeats for 240 s. The step had made
// three calls: two Cursor completed by itself (tool_call_completed with no
// tool_call_started and no exec) and the one it sent. 0.2.34 waited for the
// count's other two while Cursor waited for the one call's result.
//
// The frame sequence below is the reporter's wire trace in order (kinds and
// field numbers, which is all a trace keeps). The bytes are made up where
// the trace has only sizes: call ids, the tool's name, the count's value.
import "./nonet.mjs" // first: no request leaves this machine
import { afterEach, expect, test } from "bun:test"
import { _internal } from "./index.mjs"
import { NativeSessionPool, NATIVE_LIMITS, StepCalls, WireTrace, nativeFields, pendingCalls } from "./native-session.mjs"
import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { bin, text, uint, message, envelope } from "./native-test-wire.mjs"
const { decode } = _internal
// the trace's 195 inbound frames, in order: H heartbeat, get/set a blob
// request (get_blob/set_blob), T thinking, 8 token_delta, D
// thinking_completed, x text, partial/completed/started the call updates
// 7/3/2 of call c<n>, exec the exec_server_message (McpArgs), count
// tool_requests_listed
const TRACE = `
H get get get get get get get get get get get get get get T T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8
T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 H T 8 T 8 T 8 T 8 T
8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 T 8 D x x
8 x x x 8 x x x 8 x x x 8 x x x 8 x x 8 8 partial:c1 completed:c1 8 8 partial:c2 completed:c2 8
8 partial:c3 started:c3 exec:c3 count set set set set set set set checkpoint H H H H H H H H H H
H H H H H H H H H H H H H H`.trim().split(/\s+/)
const MCP = 15 // ToolCall.mcp_tool_call
const SEARCH = 18 // ToolCall.web_search_tool_call: a kind Cursor runs itself
const span = bin(1, Buffer.alloc(16, 7))
const iu = (n, body) => bin(1, message(bin(n, body), uint(25, 0)))
const toolCall = (kind) => bin(kind, bin(1, text(1, "args")))
const callUpdate = (n, id, kind) => iu(n, message(text(1, id), bin(2, toolCall(kind))))
const mcpArgs = (rawID) => message(text(1, "magpie-read_file"), bin(2, message(text(1, "path"), bin(2, text(3, "a.txt")))), text(3, rawID), text(4, "magpie"), text(5, "read_file"), text(9, "magpie"))
// the trace's exec has no id (field 1): McpArgs, exec_id, span context, field 55
const execMessage = (rawID) => message(bin(11, mcpArgs(rawID)), text(15, "exec-" + rawID), bin(19, span), uint(55, 0))
const state = (pending) => message(...Array.from({ length: 12 }, (_, i) => bin(1, Buffer.alloc(32, i))), ...pending.map((p) => text(4, p)), bin(5, uint(1, 9)), bin(8, Buffer.alloc(32, 9)), uint(10, 0), text(22, "cli"), uint(26, 0), text(27, "UTC"), uint(39, 0))
function body(token, i, opts) {
const [what, id] = token.split(":")
const kind = id === "c3" ? MCP : SEARCH
switch (what) {
case "H": return bin(1, bin(13, Buffer.alloc(0)))
// the trace's first get_blob has no request id
case "get": return bin(4, message(...(i > 1 ? [uint(1, i)] : []), bin(2, bin(1, Buffer.alloc(32, i))), bin(4, span)))
case "set": return bin(4, message(uint(1, i), bin(3, message(bin(1, Buffer.alloc(32, i % 250)), bin(2, text(1, "kept")))), bin(4, span)))
case "T": return iu(4, text(1, "thought"))
case "D": return iu(5, uint(1, 900))
case "8": return bin(1, bin(8, uint(1, 2)))
case "x": return iu(1, text(1, "words"))
case "partial": return callUpdate(7, id, kind)
case "completed": return opts.updates === false ? null : callUpdate(3, id, kind)
case "started": return opts.updates === false ? null : callUpdate(2, id, kind)
case "exec": return bin(2, execMessage(id))
case "count": return bin(1, bin(27, uint(1, opts.count ?? 3)))
case "checkpoint": return bin(3, state(opts.pending ?? ['{"call":"c3"}']))
}
throw new Error("fixture token " + token)
}
const wire = (opts = {}) => TRACE.map((t, i) => body(t, i, opts)).filter(Boolean)
// a stream that stays open after its frames, as Cursor's did
function open(list, onClose) {
let i = 0, wake
return {
[Symbol.asyncIterator]() { return this },
next: () => (i < list.length ? Promise.resolve({ value: list[i++], done: false }) : new Promise((r) => (wake = r))),
return: () => (onClose?.(), wake?.({ done: true }), Promise.resolve({ done: true })),
}
}
const readFile = [{ name: "read_file", description: "Read a file from disk", schema: { type: "object" }, schemaText: '{"type":"object"}' }]
async function stateless(list, extra = {}) {
const events = [], notes = []
const done = (async () => {
for await (const e of decode(open(list.map((data) => ({ data }))), { send() {}, blobs: new Map(), tools: readFile, estimate: 1, note: (n) => notes.push(n), ...extra })) {
events.push(e)
if (e.stop || e.error) return
}
})()
const timer = new Promise((r) => setTimeout(() => r("open"), 1000))
return { how: await Promise.race([done.then(() => "ended"), timer]), events, notes }
}
test("stateless: the reporter's step ends on its one call once Cursor completed the other two (#550)", async () => {
const { how, events, notes } = await stateless(wire())
expect(how).toBe("ended")
expect(events.filter((e) => e.tool).map((e) => [e.tool.name, JSON.parse(e.tool.args).path])).toEqual([["read_file", "a.txt"]])
expect(events.at(-1).stop).toBe("tool_calls")
// ended at the count, by the calls Cursor completed, before the checkpoint
expect(notes).toEqual(["completed by Cursor", "completed by Cursor"])
})
test("stateless: with no call updates, the checkpoint waiting on the one call ends the step (#550)", async () => {
const { how, events, notes } = await stateless(wire({ updates: false }))
expect(how).toBe("ended")
expect(events.filter((e) => e.tool)).toHaveLength(1)
expect(events.at(-1).stop).toBe("tool_calls")
expect(notes).toEqual(["waited on"])
})
test("stateless: a checkpoint waiting on more calls than came does not end the step (#550)", async () => {
const { how } = await stateless(wire({ updates: false, pending: ["c3", "c4"] }))
expect(how).toBe("open")
})
test("stateless: a quiet Run's error says what came of the step's calls (#550)", async () => {
const list = wire({ updates: false, pending: ["c3", "c4"] }).map((data) => ({ data }))
async function* quiet() {
yield* list
throw Object.assign(new Error("Cursor went quiet: 24 heartbeats and nothing else for 240 s (try again)"), { quiet: true, status: 502 })
}
const events = []
for await (const e of decode(quiet(), { send() {}, blobs: new Map(), tools: readFile, estimate: 1 })) events.push(e)
expect(events.at(-1).error.message).toBe("Cursor went quiet: 24 heartbeats and nothing else for 240 s; the step's tool count 3: 1 calls came, 0 answered here, 0 completed by Cursor (try again)")
})
test("StepCalls: a completion counts once, only for a call this step wrote and never started or sent", () => {
const s = new StepCalls(nativeFields)
const uf = (id) => nativeFields(text(1, id))
// written, then completed: Cursor's own
expect(s.update(7, uf("a"))).toBe(false)
expect(s.update(3, uf("a"))).toBe(true)
expect(s.update(3, uf("a"))).toBe(false)
// started on the client: its completion is the result coming back
s.update(7, uf("b"))
s.update(2, uf("b"))
expect(s.update(3, uf("b"))).toBe(false)
// sent as an exec (its id among the exec's args), with no start
s.update(7, uf("call-d"))
s.exec(execMessage("call-d"))
expect(s.update(3, uf("call-d"))).toBe(false)
expect(s.completed).toBe(1)
// an earlier step's call completing in this one is not counted again
s.nextStep()
expect(s.completed).toBe(0)
expect(s.update(3, uf("e"))).toBe(false)
expect(s.completed).toBe(0)
})
test("pendingCalls reads the checkpoint's pending_tool_calls", () => {
expect(pendingCalls(state(["x"]))).toBe(1)
expect(pendingCalls(state([]))).toBe(0)
expect(pendingCalls(Buffer.from([0x0a, 0x05]))).toBe(null)
})
test("Wire trace: a trace keeps the count's number, each call update's kind, the checkpoint's pending count and why the Run was stateless (#550)", () => {
const dir = mkdtempSync(join(tmpdir(), "cursor-trace-550-"))
try {
const trace = new WireTrace(dir, { path: "stateless", model: "synthetic-model", why: "retention capacity or reservation unavailable" })
for (const data of wire()) if (!data.equals(bin(1, bin(13, Buffer.alloc(0))))) trace.frame("in", { data })
trace.event("completed by Cursor")
trace.write({ status: 502, message: "synthetic" })
const body = JSON.parse(readFileSync(join(dir, readdirSync(dir)[0]), "utf8"))
expect(body.why).toBe("retention capacity or reservation unavailable")
const kept = body.frames.filter((f) => f.count != null || f.tool || f.pending != null).map(({ count, tool, pending }) => ({ count, tool, pending }))
expect(kept).toEqual([
{ tool: [SEARCH, 1] }, { tool: [SEARCH, 1] }, { tool: [SEARCH, 1] }, { tool: [SEARCH, 1] },
{ tool: [MCP, 1] }, { tool: [MCP, 1] },
{ count: 3 },
{ pending: 1 },
].map((e) => ({ count: undefined, tool: undefined, pending: undefined, ...e })))
expect(body.frames.at(-1)).toMatchObject({ event: "completed by Cursor" })
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
// the native path, the same frames
const pools = []
afterEach(async () => { await Promise.all(pools.splice(0).map((p) => p.clear())) })
function owner(overrides = {}) {
const pool = new NativeSessionPool({ ...NATIVE_LIMITS, ...overrides })
pools.push(pool)
const prepared = pool.prepare("synthetic-token", { model: "synthetic-model", messages: [{ role: "user", content: "synthetic" }] }, "synthetic-session", readFile)
const run = pool.create(prepared, { id: "synthetic-model", maxMode: false, params: [] }, _internal)
run.chatTools = readFile
run.bind({ send() {}, close() {} }, new Map(), 11)
return run
}
const until = async (predicate) => {
const deadline = Date.now() + 5000
while (!predicate()) {
if (Date.now() >= deadline) throw new Error("fixture did not reach its expected state")
await new Promise((r) => setTimeout(r, 5))
}
}
const nativeFrames = (opts) => wire(opts).map((b) => ({ data: envelope(b).subarray(5) }))
// pending: a checkpoint that waits on more than came, so only the calls
// Cursor completed can seal it
for (const [name, opts] of [["call updates", { pending: ["c3", "c9"] }], ["the checkpoint alone", { updates: false }]]) test(`native: the reporter's step seals on its one call, by ${name} (#550)`, async () => {
const run = owner({ batchWait: 2000 })
run.pump(open(nativeFrames(opts)))
await until(() => run.error || run.state === "awaiting-results")
expect(run.error).toBeUndefined()
expect(run.segment.events.filter((e) => e.tool).map((e) => e.tool.name)).toEqual(["read_file"])
expect(run.segment.events.at(-1).stop).toBe("tool_calls")
})
test("native: a step still short of its count fails batchWait, naming the calls Cursor completed (#550)", async () => {
const run = owner({ batchWait: 200 })
run.pump(open(nativeFrames({ count: 4, pending: ["c3", "c4"] })))
await until(() => run.error)
expect(run.error.message).toMatch(/^Cursor did not complete its declared native tool batch: 1 of 4 calls came, 0 answered here, 2 completed by Cursor/)
})