From 33cdf7c1a8fc96efa6513d5871623962ed8b0e14 Mon Sep 17 00:00:00 2001 From: nicegui <147186267+nicegui@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:39:14 +0800 Subject: [PATCH] cursor: Run tool calls stay on one native Cursor session and resume stateless after a long tool, not a failed turn (#135, nicegui) Cursor's Run (native) calls stay on one Cursor session across a tool result. With them, a tool that runs longer than Cursor's limit resumes stateless, not as a failed turn. The session pool lives in native-session.mjs. It applies to a conversation's first user turn, and a new user turn goes stateless (see the README). X-Magpie-Cursor-Continuity says which path a request took. The dashboard-usage ledger counts two distinct events in one response that share a millisecond, as main did. Only timestamps claimed by earlier fetches are left out. A new deferred-usage test covers it. Run at the reviewed head 398aeddc0186cfc38189b1f05577b181aa2d587d (merge base 5d5d86e; main has no packages/cursor change since): - packages/cursor `bun test` 3 times: 258 pass, 0 fail each time. - `bun test latency` 12 times with fresh HOMEs: 12/12 pass. - Broken by hand: putting back `if (claimed.has(key + "\0" + ev.timestamp) || at >= before()) continue` makes the new test "distinct same-millisecond events in one response are billed together, not again on later fetches" fail (2 pass, 1 fail). The head's line passes. - `bun scripts/check.mjs`: all packages pass. - `npm pack`, extracted into a fresh dir: index.mjs, native-session.mjs, package.json, README.md. `import("./index.mjs")` exports CursorAuthPlugin and _internal, and native-session.mjs imports. - CI: test and on-npm green. Not tried: a real Cursor account. The owner's stored plugin sign-in has no access token. The author reports a real Claude Code run through an isolated gateway: a child resumed stateless after a 125s tool, and all 6 requests returned 200. --- packages/cursor/README.md | 47 +- packages/cursor/deferred-usage.test.mjs | 28 + packages/cursor/index.mjs | 504 ++++++-- packages/cursor/latency.test.mjs | 10 +- packages/cursor/native-e2e.test.mjs | 1387 +++++++++++++++++++++++ packages/cursor/native-http1.test.mjs | 260 +++++ packages/cursor/native-session.mjs | 845 ++++++++++++++ packages/cursor/native-session.test.mjs | 203 ++++ packages/cursor/native-test-wire.mjs | 90 ++ packages/cursor/open.test.mjs | 20 +- packages/cursor/package.json | 2 +- 11 files changed, 3302 insertions(+), 94 deletions(-) create mode 100644 packages/cursor/native-e2e.test.mjs create mode 100644 packages/cursor/native-http1.test.mjs create mode 100644 packages/cursor/native-session.mjs create mode 100644 packages/cursor/native-session.test.mjs create mode 100644 packages/cursor/native-test-wire.mjs diff --git a/packages/cursor/README.md b/packages/cursor/README.md index dd250d2..0696c1b 100644 --- a/packages/cursor/README.md +++ b/packages/cursor/README.md @@ -35,7 +35,7 @@ plugin's `fetch` answers them on Cursor's agent API: the account (a team may be served in one region only), else `agentn.global.api5.cursor.sh`. A refusal that names a region is tried once more with the config asked again. -- Each request is one `agent.v1.AgentService/Run`, a Connect stream both +- A fresh request opens `agent.v1.AgentService/Run`, a Connect stream both ways over HTTP/2, with the CLI's headers (`x-cursor-client-type: cli`, its version, privacy mode on). - Where HTTP/2 can't open a Run (an error before its response, or none in @@ -50,7 +50,7 @@ plugin's `fetch` answers them on Cursor's agent API: to try HTTP/2 again. A region error over HTTP/1.1 sends the Run back to HTTP/2 at the region's agent host. A BidiAppend with no answer in 60 s (more for a large one) ends the Run, as cursor-agent does. -- The whole conversation goes each time, as AI SDK messages kept as blobs +- A new Run imports the whole conversation as AI SDK messages kept as blobs the server asks for. The caller's tools are MCP tools, listed in the system prompt; the model calls them through Cursor's `CallDynamicTool`, and the calls come back as chat completion tool calls. Cursor's own tools @@ -90,6 +90,49 @@ plugin's `fetch` answers them on Cursor's agent API: Failures keep their statuses: 401 to sign in again, 429 at the usage limit, 400 for a prompt too long, 403 for a region refusal. +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. The pool holds at most 8 owners per account and 32 per process, with +bounded history, blobs, arguments, and pending writes. + +These are retention limits. A missing, expired, restarted, busy, incompatible, +or full owner uses the original history reconstruction and stateless decoder +on a new Run. Pending parent calls and new input can take that path without +cancelling the parent's owner. Already supplied client tool results become +history; the plugin never executes those external tools. A failed native result +write is reported to that request because its outcome may be uncertain. A later +request can rebuild from its supplied history without submitting the result to +the old native exec again. + +A native tool handoff reports zero usage with `magpie_native.accounting=pending`; +the final native answer reports the turn's totals. An identical completed retry +replays the saved response with zero usage. A native final also collects earlier +stateless debt as `usage.magpie_deferred`, separately from its own prompt total. +If a started native Run is abandoned after a pending handoff, its dashboard +count is owed once to the same account and conversation. Successful final +snapshots, including explicit zero, and cached replays do not enroll that debt. + +Dashboard attribution uses event timestamps, rather than when events arrive. +Older debt is bounded strictly before the native Run's start, and keeps that +bound across later stateless Runs so an authoritative native event is not +billed again. An earlier event stamped on or after that boundary cannot be +identified reliably and stays unknown. Missing or ambiguous debt expires after +10 minutes; at most 64 distinct bounded debt groups are kept per account and +conversation, dropping the oldest on overflow. These counts are never guessed +as prior usage. Stateless Runs otherwise keep the dashboard accounting above. +`X-Magpie-Cursor-Continuity` identifies `same-run` or `stateless`, with the fallback +reason where available. A missing native batch count can retry stateless once +before any output is exposed or native result submitted; progressive output is +kept and its later errors are surfaced. + +The existing request builder and model selection remain in use, including the +legacy `thinking=false` mapping for explicit `none`/`off`. Retention adds no +request-field whitelist or strict generation-option validation. Native tool +results preserve ordered text and data-URL images and explicit error flags; +unsupported native result shapes use the legacy history path. + ## Models The `config` hook declares `auto` (Cursor's pick). Once signed in, the diff --git a/packages/cursor/deferred-usage.test.mjs b/packages/cursor/deferred-usage.test.mjs index 06dc3d8..0794a3a 100644 --- a/packages/cursor/deferred-usage.test.mjs +++ b/packages/cursor/deferred-usage.test.mjs @@ -73,6 +73,34 @@ test("a step's prompt_tokens is its own Run's; what it collected of an earlier s expect(u1.prompt_tokens + u2.prompt_tokens + u2.magpie_deferred.prompt_tokens).toBe(prompt(E1) + prompt(E2)) }) +test("distinct same-millisecond events in one response are billed together, not again on later fetches", async () => { + Object.assign(STEP_WAIT, { first: 0, every: 1, until: 5, owedAt: 60_000 }) + const tok = "same-millisecond-account", conv = "same-millisecond-conversation" + const since = Date.now() - 30_000 + let shown = [] + globalThis.fetch = async () => Response.json({ usageEventsDisplay: shown }) + const first = await step(ledger(tok, conv, since, undefined, true)) + const second = await step(ledger(tok, conv, since + 1, undefined, true)) + expect([first.prompt_tokens, second.prompt_tokens]).toEqual([0, 0]) + const timestamp = String(since + 2000) + shown = [E1, E2].map((tokenUsage) => ({ timestamp, conversationId: conv, tokenUsage })) + const final = ledger(tok, conv, Date.now(), undefined, true) + const billed = await final.owed(true) + final.done() + expect(billed).toMatchObject({ + input: E1.inputTokens + E2.inputTokens, + output: E1.outputTokens + E2.outputTokens, + cacheRead: E1.cacheReadTokens + E2.cacheReadTokens, + cacheWrite: E1.cacheWriteTokens + E2.cacheWriteTokens, + }) + expect(owed.has(_internal.usageKey(tok, conv))).toBe(false) + // The response was counted once. Another Run seeing that same response + // must not bill either event again, even though both share a timestamp. + const next = await step(ledger(tok, conv, since + 2, undefined, true)) + expect(next.prompt_tokens).toBe(0) + expect(next.magpie_deferred).toBeUndefined() +}) + test("a step that owed nothing has no magpie_deferred", async () => { Object.assign(STEP_WAIT, { first: 0, every: 10, until: 200, owedAt: 0 }) const conv = "8a462df8-0000-4000-8000-000000000002" diff --git a/packages/cursor/index.mjs b/packages/cursor/index.mjs index 11f0ee6..43be16c 100644 --- a/packages/cursor/index.mjs +++ b/packages/cursor/index.mjs @@ -21,13 +21,15 @@ // a conversation, the caller's system prompt at its head; the Run only // resumes it. The caller's tools are MCP tools, which the model calls // through Cursor's CallDynamicTool: the server hands each call to the -// client to run, and once it has said how many a step made, the stream is -// closed and the calls go back to OpenCode as a chat completion's tool -// calls. Nothing else the server asks the client to run (a shell, a file -// read) is run. +// client to run, and once it has said how many a step made, the calls +// go back to OpenCode. When the owner is available their results continue +// that Run; otherwise the caller's history starts a stateless Run. Nothing +// else the server asks the client to run (a shell, a file read) is run. // // OpenCode speaks chat completions to it (@ai-sdk/openai-compatible); the // fetch here answers them. +import { NATIVE_LIMITS, nativeSessions, NativeSessionError, nativeFields, nativeMcpArgs } from "./native-session.mjs" +import { isDeepStrictEqual } from "node:util" import http2 from "node:http2" import { STATUS_CODES } from "node:http" import { gunzipSync } from "node:zlib" @@ -1396,14 +1398,43 @@ function addUsage(a, b) { return a } -// owe adds to the account/conversation's debt. -function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null }) { - for (const [k, d] of owed) if (Date.now() - d.since > STEP_WAIT.owedFor) owed.delete(k) +// owe adds to the account/conversation's debt. A native Run bounds older +// event timestamps before its start: its authoritative final must never be +// collected as an earlier Run. Keep that bound when a later stateless Run +// adds unbounded debt. Ordinary stateless debt retains its original shape. +const DEBT_GROUP_LIMIT = 64 +function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null, before }) { + for (const [k, d] of owed) { + if (d.groups) { + d.groups = d.groups.filter((g) => Date.now() - g.since <= STEP_WAIT.owedFor) + d.n = d.groups.reduce((sum, g) => sum + g.n, 0) + if (Date.now() - d.since > STEP_WAIT.owedFor) d.carry = null + if (!d.n && !d.carry) owed.delete(k) + else if (d.groups.length) d.since = Math.min(...d.groups.map((g) => g.since)) + } else if (Date.now() - d.since > STEP_WAIT.owedFor) owed.delete(k) + } if (n <= 0 && !carry) return const d = owed.get(key) - if (!d) return void owed.set(key, { since, n, ready, carry: carry && { ...carry } }) - d.since = Math.min(d.since, since) - d.n += n + if (!d) return void owed.set(key, { since, n, ready, carry: carry && { ...carry }, ...(before !== undefined ? { before } : {}) }) + if (n > 0 && (d.groups || d.before !== undefined || before !== undefined)) { + const groups = d.groups ?? (d.n > 0 ? [{ since: d.since, n: d.n, ready: d.ready, before: d.before }] : []) + const same = groups.find((g) => g.before === before) + if (same) { + same.since = Math.min(same.since, since) + same.n += n + same.ready = Math.min(same.ready, ready) + } else groups.push({ since, n, ready, before }) + // As with expired dashboard debt, overflow stays unknown, never estimated + // or merged across bounds into an authoritative native Run's event. + groups.sort((a, b) => a.since - b.since) + d.groups = groups.slice(-DEBT_GROUP_LIMIT) + delete d.before + d.n = d.groups.reduce((sum, g) => sum + g.n, 0) + d.since = Math.min(...d.groups.map((g) => g.since)) + } else { + d.since = Math.min(d.since, since) + d.n += n + } d.ready = Math.min(d.ready, ready) d.carry = addUsage(d.carry, carry) } @@ -1414,7 +1445,7 @@ function owe(key, { since = Date.now(), n = 0, ready = Date.now(), carry = null // when the account can't read them. // Polling, they are looked for as STEP_WAIT says, from `first` on, until // all show; else asked for once. -async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_WAIT.first, signal } = {}) { +async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_WAIT.first, signal, before = () => Infinity, groups, abortFetch = false } = {}) { const key = usageKey(tok, conv) const end = Date.now() + STEP_WAIT.until const wait = (ms) => new Promise((r) => { @@ -1426,6 +1457,7 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_ let usage = null let got = 0 const events = [] + const counts = groups?.map(() => 0) if (poll) await wait(first) while (!signal?.aborted) { try { @@ -1433,19 +1465,26 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_ method: "POST", headers: await headersFor(tok), body: JSON.stringify({ teamId: 0, startDate: String(since - 60_000), endDate: String(Date.now() + 60_000), page: 1, pageSize: 50 }), - signal: AbortSignal.timeout(STEP_WAIT.ask), + signal: abortFetch && signal ? AbortSignal.any([signal, AbortSignal.timeout(STEP_WAIT.ask)]) : AbortSignal.timeout(STEP_WAIT.ask), }) if (res.status >= 400 && res.status < 500 && res.status !== 429) { // not this account's to read unreadable.set(tokKey(tok), Date.now()) - return { usage, events, got, refused: true } + return { usage, events, got, counts, refused: true } } const evs = res.ok ? ((await res.json())?.usageEventsDisplay ?? []) : [] const found = evs .filter((e) => e?.conversationId === conv && e.tokenUsage && num(e.timestamp) >= since - 1000 && !claimed.has(key + "\0" + e.timestamp)) .sort((a, b) => num(a.timestamp) - num(b.timestamp)) - .slice(0, want - got) for (const ev of found) { + if (got >= want) break + const at = num(ev.timestamp) + // found already excludes timestamps claimed by earlier fetches. Two + // distinct events in this response may share a millisecond; count both. + if (at >= before()) continue + const group = groups?.findIndex((g, i) => counts[i] < g.n && at >= g.since - 1000 && at < (g.before ?? Infinity)) + if (groups && group === -1) continue + if (groups) counts[group]++ claimed.set(key + "\0" + ev.timestamp, Date.now()) const t = ev.tokenUsage const u = { input: num(t.inputTokens), output: num(t.outputTokens), cacheRead: num(t.cacheReadTokens), cacheWrite: num(t.cacheWriteTokens), reasoning: 0 } @@ -1458,7 +1497,7 @@ async function usageEvents(tok, conv, since, want, { poll = false, first = STEP_ if (!poll || Date.now() + STEP_WAIT.every > end) break await wait(STEP_WAIT.every) } - return { usage, events, got, refused: false } + return { usage, events, got, counts, refused: false } } // stepUsage is the usage of the Run of conversation conv started at since, @@ -1472,22 +1511,35 @@ async function stepUsage(tok, conv, since, signal) { // what was carried alone (carry) and the events found (events), and whether any is // still owed (short), which is owed on. What comes back once the Run that // asked is over (over() true) is carried to the next instead. -function collect(tok, conv, { poll = false, first, signal, over = () => false } = {}) { +function collect(tok, conv, { poll = false, first, signal, over = () => false, abortFetch = false } = {}) { const key = usageKey(tok, conv) const d = owed.get(key) if (!d) return Promise.resolve({ usage: null, carry: null, events: [], short: false }) owed.delete(key) const p = (async () => { + const groups = (d.groups ?? [d]).filter((g) => (g.before === undefined && !d.groups) || Date.now() - g.since <= STEP_WAIT.owedFor) + const want = groups.reduce((sum, g) => sum + g.n, 0) let r = { usage: null, events: [], got: 0 } - if (d.n > 0 && canRead(tok)) r = await usageEvents(tok, conv, d.since, d.n, { poll, first, signal }).catch(() => r) - const short = d.n > r.got && canRead(tok) - if (short) owe(key, { since: d.since, n: d.n - r.got, ready: d.ready }) + if (want > 0 && canRead(tok)) r = await usageEvents(tok, conv, Math.min(...groups.map((g) => g.since)), want, { + poll, first, signal, abortFetch, before: () => d.before ?? Infinity, ...(d.groups ? { groups } : {}), + }).catch(() => r) + let short = false + for (const [i, g] of groups.entries()) { + const remaining = g.n - (d.groups ? r.counts?.[i] ?? 0 : r.got) + if (remaining > 0 && canRead(tok)) { + short = true + owe(key, { since: g.since, n: remaining, ready: g.ready, before: g.before }) + } + } const carry = d.carry && { ...d.carry } const usage = addUsage(d.carry, r.usage) if (!over()) return { usage, carry, events: r.events ?? [], short } owe(key, { carry: usage }) return { usage: null, carry: null, events: [], short } })() + // Native admission may happen while an older collector is still in flight. + // Its dynamic event bound must apply before that response is claimed too. + p.debt = d const set = flights.get(key) ?? new Set() flights.set(key, set.add(p)) p.finally(() => { @@ -1517,14 +1569,18 @@ function collect(tok, conv, { poll = false, first, signal, over = () => false } // owed(), apart. A Run of its conversation begins only once the one // before has ended, so the two never meet; were the time off, the step's // count would be told in the wrong field, never twice nor lost. -function ledger(tok, conv, since, signal, kept) { +function ledger(tok, conv, since, signal, kept, { before } = {}) { const key = tokKey(tok) const debtKey = usageKey(tok, conv) + if (kept && before !== undefined) { + const debts = [owed.get(debtKey), ...[...(flights.get(debtKey) ?? [])].map((p) => p.debt)] + for (const d of debts) for (const g of d?.groups ?? (d ? [d] : [])) g.before = Math.min(g.before ?? Infinity, before) + } let mine = null // this Run's own, collected, not given out yet let theirs = null // earlier Runs', collected, not given out yet let over = false const gather = (opts) => - collect(tok, conv, { ...opts, over: () => over }).then((r) => { + collect(tok, conv, { ...opts, over: () => over, abortFetch: before !== undefined }).then((r) => { theirs = addUsage(theirs, r.carry) for (const e of r.events ?? []) { if (e.at >= since - 1000) mine = addUsage(mine, e.usage) @@ -1876,6 +1932,206 @@ function openH1(headers, signal) { return Promise.resolve(signal?.aborted ? cancelledOpen() : { session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true }) } +// Every outbound frame, including KV replies and heartbeats, uses the same +// bounded FIFO. Admission is synchronous; a result is reserved only once even +// when a later write fails. Count bytes until both callback and drain complete. +function nativeTransport(req, close, fail, limits = NATIVE_LIMITS) { + const outbound = { bytes: 0, messages: 0 } + const queue = [] + let closed = false, flushing = false, rejectWrite + const flush = async () => { + if (closed || flushing) return + flushing = true + try { + while (!closed && queue.length) { + const packet = queue.shift() + await new Promise((resolve, reject) => { + let written = false, drained = false, started = false, settled = false + const finish = (error) => { + if (settled) return + settled = true + rejectWrite = undefined + req.removeListener("drain", drain) + req.removeListener("error", failed) + req.removeListener("close", lost) + error ? reject(error) : resolve() + } + const check = () => { if (started && written && drained) finish() } + const drain = () => { drained = true; check() } + const failed = (e) => finish(e) + const lost = () => finish(new NativeSessionError(502, "native transport closed during a write; its outcome is uncertain")) + rejectWrite = finish + req.once("drain", drain) + req.once("error", failed) + req.once("close", lost) + try { + drained = req.write(packet, (e) => { + if (e) return finish(e) + written = true + check() + }) || drained + started = true + if (drained) req.removeListener("drain", drain) + check() + } catch (e) { finish(e) } + }) + if (!closed) { outbound.bytes -= packet.length; outbound.messages-- } + } + } catch (e) { + if (!closed) fail(e) + } finally { flushing = false } + } + return { + outbound, + send(message) { + if (closed || req.destroyed || !req.writable) throw new NativeSessionError(502, "native transport is no longer writable") + const size = message.length + 5 + if (outbound.bytes + size > limits.outboundBytes) throw new NativeSessionError(503, "native outbound bytes limit reached") + if (outbound.messages + 1 > limits.outboundMessages) throw new NativeSessionError(503, "native outbound messages limit reached") + outbound.bytes += size + outbound.messages++ + queue.push(frame(message)) + void flush() + }, + close() { + if (closed) return + closed = true + queue.length = 0 + outbound.bytes = 0 + outbound.messages = 0 + rejectWrite?.(new NativeSessionError(410, "native transport was cancelled")) + close() + }, + } +} + +// runNative opens a session-owned Run. Its background decoder survives the end +// of each Chat segment; only terminal completion, failure, or cancellation +// releases the transport. +async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, params, native }) { + const cid = convID || randomUUID() + const since = Date.now() + // Transport shutdown precedes final debt collection. Keep its cancellation + // separate, and return any undelivered collection through the ledger's carry. + const accounting = new AbortController() + const book = ledger(tok, cid, since, accounting.signal, !!convID, { before: since }) + const debtKey = usageKey(tok, cid) + let started = false, settled = false, deferred = null + native.accounting = { + started() { started = true }, + async settle() { + const more = await book.owed(true) + if (settled) { + if (more) owe(debtKey, { carry: more }) + return null + } + deferred = more + return more + }, + delivered() { + if (settled) return + settled = true + deferred = null + book.done() + accounting.abort() + }, + abandon() { + if (settled) return + settled = true + book.done() + accounting.abort() + if (deferred) owe(debtKey, { carry: deferred }) + deferred = null + // Every handoff of this owner belongs to one Run. Only an abandoned + // started/pending Run is owed; a final snapshot (including zero) is not. + if (started && native.segments > 0 && !native.finalUsage && convID && canRead(tok)) { + owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt }) + } + }, + } + const { first, blobs } = buildRun(conv.msgs, conv.last, tools, id, cid, { maxMode, params }) + native.chatTools = tools + native.attach(signal) + if (native.error) { + nativeSessions.forget(native) + return { error: native.error } + } + const o = await open( + base, + { + "content-type": "application/connect+proto", + "connect-protocol-version": "1", + authorization: `Bearer ${tok}`, + "x-cursor-client-version": await clientVersion(), + "x-cursor-client-type": "cli", // else Cursor adds a prompt of its own + "x-ghost-mode": "true", // privacy mode: nothing kept for training + "x-request-id": randomUUID(), + // none of Cursor's own tools, only the caller's + "x-cursor-agent-allowed-tools": "mcp_tool_call,get_mcp_tools_tool_call", + }, + native.ac.signal, + ) + if (o.error) { + native.fail(o.error) + nativeSessions.forget(native) + return o + } + const { session, req } = o + const close = () => { + try { req.close(http2.constants.NGHTTP2_CANCEL) } catch {} + session.close() + session.destroy() + } + const transport = nativeTransport(req, close, (e) => native.fail({ status: e.status ?? 502, message: e.message }), native.limits) + try { + native.bind(transport, blobs, conv.estimate) + if (native.error) { + nativeSessions.forget(native) + return { error: native.error } + } + native.send(first) + native.accounting.started() + if (o.status < 200 || o.status > 299) { + const chunks = [] + for await (const c of req) chunks.push(c) + native.fail(failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20))) + nativeSessions.forget(native) + return { error: native.error, h1: !!o.h1 } + } + native.pumpTask = (async () => { + await native.pump(frames(req)) + })() + const response = native.response() + const it = response.events + const head = await it.next() + if (head.done || head.value.error) { + const error = head.value?.error ?? { status: 502, message: "an empty reply" } + await native.cancel(error.message) + nativeSessions.forget(native) + return { error, h1: !!o.h1 } + } + let firstEvent = head + response.events = { + next() { + if (firstEvent) { + const r = firstEvent + firstEvent = null + return Promise.resolve(r) + } + return it.next() + }, + return: () => it.return(), + [Symbol.asyncIterator]() { return this }, + } + return response + } catch (e) { + native.fail({ status: e.status ?? 502, message: e.message }) + await native.pumpTask + nativeSessions.forget(native) + return { error: native.error, h1: !!o.h1 } + } +} + // 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 }) { @@ -2174,18 +2430,50 @@ function emptyWhy(how, seen, usage) { // exec answers what the server asks the client to run: a call of the // caller's tools is returned, the list of them is given, and anything else // is refused. -function exec(msg, tools, send, closeExec, refused) { - const es = fields(msg) +function exec(msg, tools, send, closeExec, refused, native = false) { + const es = native ? nativeFields(msg) : fields(msg) + // ExecServerMessage.id is a proto3 uint32: an omitted field means zero. + // Explicit malformed fields must not acquire that valid default. + if (native && es.some((e) => e.num === 1 && (e.wire !== 0 || !Number.isInteger(e.n) || e.n < 0 || e.n > 0xffffffff))) + throw new NativeSessionError(502, "invalid native exec request ID") const id = pbNum(es, 1) const execID = pbStr(es, 15) + // Validate every MCP envelope before any exec can publish a call or send a + // response. Differing duplicates have no supported selection/merge contract. + let nativeCall, nativeUnavailable = false + if (native) for (const e of es) if (e.num === 11) { + if (e.wire !== 2) throw new NativeSessionError(502, "invalid native MCP argument envelope") + const { fields: a, args } = nativeMcpArgs(e.data) + const name = pbStr(a, 5) || pbStr(a, 1).replace(/^magpie-/, "") + const provider = pbStr(a, 4) + const server = pbStr(a, 9) + if (provider && provider !== "magpie" || server && server !== "magpie") nativeUnavailable = true + if (pbNum(a, 7) || field(a, 6)) nativeUnavailable = true + if (!tools.some((t) => t.name === name)) nativeUnavailable = true + if (!pbStr(a, 5) && pbStr(a, 1) !== "magpie-" + name) nativeUnavailable = true + const call = { requestID: id, execID, nativeID: pbStr(a, 3), name, args } + if (nativeCall && !isDeepStrictEqual(nativeCall, call)) throw new NativeSessionError(502, "ambiguous repeated native MCP argument envelopes") + nativeCall ??= call + } const answer = (num, res) => { send(pb().bytes(2, pb().varint(1, id).str(15, execID).bytes(num, res)).done()) closeExec(id) } + const unavailable = () => { + const kind = es.find((e) => ![1, 15, 19, 55].includes(e.num))?.num ?? 0 + refused?.set(kind, (refused.get(kind) ?? 0) + 1) + send(pb().bytes(5, pb().bytes(2, pb().varint(1, id).str(2, "not available"))).done()) + closeExec(id) + return null + } + // A foreign/unregistered MCP or approval flow is unavailable to this bridge. + // Refuse it like a native shell request, then let the model continue. + if (nativeUnavailable) return unavailable() for (const e of es) { switch (e.num) { case 11: { // mcp_args: a call of the caller's tools + if (native) return { ...nativeCall, args: JSON.stringify(nativeCall.args) } const a = fields(e.data) const args = {} for (const kv of a) { @@ -2213,11 +2501,7 @@ function exec(msg, tools, send, closeExec, refused) { } } // a shell, a file read or an edit of Cursor's own: never run - const kind = es.find((e) => e.num !== 1 && e.num !== 15)?.num ?? 0 - refused?.set(kind, (refused.get(kind) ?? 0) + 1) - send(pb().bytes(5, pb().bytes(2, pb().varint(1, id).str(2, "not available"))).done()) - closeExec(id) - return null + return unavailable() } // ---- chat completions ------------------------------------------------------------------ @@ -2258,67 +2542,117 @@ async function answerOf(auth, chat, signal, session = "") { } catch (e) { return errorResponse({ status: e.status ?? 401, message: e.message }) } - const model = String(chat.model ?? "") - let raw = [] - try { - raw = await usable(tok) - } catch {} - // fast only when asked: a service_tier of priority or fast is on; any - // other tier, or none, is off, unless the id is a fast one of Cursor's own - const tier = chat.service_tier - const fast = tier === "priority" || tier === "fast" ? true : tier ? false : undefined - const req = request(raw, model, chat.reasoning_effort ?? "", fast) - const id = req.id - const params = req.params - let maxMode = req.maxMode || maxOnly.has(id) + if (signal?.aborted) return errorResponse({ status: 410, message: "the request was cancelled" }) const tools = toolsOf(chat) - const conv = conversation(chat, tools) const convID = conversationID(chat, session) - let base = await agentURL(tok, false) - const once = () => runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params }) - let r = await once() - if (r.error && regional(r.error.message)) { - // the team moved, or the config was kept from before: once more with - // what the config says now. A Run that went over HTTP/1.1 went to api2, - // not the region's agent host: once more over HTTP/2 there. - const viaH1 = !!r.h1 - h1Until = 0 - const fresh = await agentURL(tok, true) - if (fresh !== base || viaH1) { - base = fresh + const prepared = nativeSessions.prepare(tok, chat, convID, tools) + let r + if (prepared.owner) r = prepared.owner.resume(prepared, signal) + const model = String(chat.model ?? "") + if (!r) { + let raw = [] + try { + raw = await usable(tok) + } catch {} + // fast only when asked: a service_tier of priority or fast is on; any + // other tier, or none, is off, unless the id is a fast one of Cursor's own + const tier = chat.service_tier + const fast = tier === "priority" || tier === "fast" ? true : tier ? false : undefined + const req = request(raw, model, chat.reasoning_effort ?? "", fast) + const id = req.id + const params = req.params + let maxMode = req.maxMode || maxOnly.has(id) + const conv = conversation(chat, tools) + let base = await agentURL(tok, false) + const once = async () => { + // Retention is an optimization. Admission pressure or unavailable ownership + // 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) + const rebuild = async () => { + const fallback = await runOnce(args) + fallback.diagnostic = "stateless; bootstrap=imported-history; reason=missing-batch-count" + return fallback + } + // A missing native batch count may be retried once, only before Chat + // output is exposed or any native result was submitted. Never repeat an + // uncertain tool result write or duplicate a progressive stream's output. + if (response.error?.retentionIneligible && !signal?.aborted) response = await rebuild() + else if (native) response.rebuild = rebuild + response.diagnostic ??= "stateless; bootstrap=imported-history; reason=" + (prepared.fallback || "retention capacity or reservation unavailable") + return response + } + r = await once() + if (r.error && regional(r.error.message)) { + // the team moved, or the config was kept from before: once more with + // what the config says now. A Run that went over HTTP/1.1 went to api2, + // not the region's agent host: once more over HTTP/2 there. + const viaH1 = !!r.h1 + h1Until = 0 + const fresh = await agentURL(tok, true) + if (fresh !== base || viaH1) { + base = fresh + r = await once() + } + } + if (r.error && !maxMode && maxRequired(r.error.message)) { + // a model Cursor serves only in Max Mode that neither list said so of: + // in Max Mode, as the CLI turns it on for such a model, and so from + // now on. An account Max Mode isn't open to is answered as Cursor + // answers that. + maxMode = true + maxOnly.add(id) r = await once() } } - if (r.error && !maxMode && maxRequired(r.error.message)) { - // a model Cursor serves only in Max Mode that neither list said so of: - // in Max Mode, as the CLI turns it on for such a model, and so from - // now on. An account Max Mode isn't open to is answered as Cursor - // answers that. - maxMode = true - maxOnly.add(id) - r = await once() - } if (r.error) return errorResponse(r.error) + // A resumed owner may fail while submitting results. Surface that uncertain + // write once; later history rebuilds never submit it again on that owner. const it = r.events + let head = await it.next() + if (head.value?.error) return errorResponse(head.value.error) + let events = { + next() { + if (head) { const value = head; head = null; return Promise.resolve(value) } + return it.next() + }, + return: () => it.return?.(), + [Symbol.asyncIterator]() { return this }, + } + const responseHeaders = { "X-Magpie-Cursor-Continuity": r.diagnostic } const cid = "chatcmpl-" + randomBytes(12).toString("hex") const created = Math.floor(Date.now() / 1000) if (!chat.stream) { - const msg = { role: "assistant", content: "" } - let reasoning = "" - const calls = [] - let stop = "stop" - let usage - for await (const e of it) { - if (e.error) return errorResponse(e.error) - if (e.text) msg.content += e.text - if (e.reasoning) reasoning += e.reasoning - if (e.tool) calls.push({ id: e.tool.id, type: "function", function: { name: e.tool.name, arguments: e.tool.args } }) - if (e.stop) [stop, usage] = [e.stop, e.usage] + while (true) { + let retry = false + const msg = { role: "assistant", content: "" } + let reasoning = "" + const calls = [] + let stop = "stop" + let usage + for await (const e of events) { + if (e.error) { + if (!e.error.retentionIneligible || !r.rebuild || signal?.aborted) return errorResponse(e.error) + r = await r.rebuild() + if (r.error) return errorResponse(r.error) + events = r.events + responseHeaders["X-Magpie-Cursor-Continuity"] = r.diagnostic + retry = true + break + } + if (e.text) msg.content += e.text + if (e.reasoning) reasoning += e.reasoning + if (e.tool) calls.push({ id: e.tool.id, type: "function", function: { name: e.tool.name, arguments: e.tool.args } }) + if (e.stop) [stop, usage] = [e.stop, e.usage] + } + if (retry) continue + if (reasoning) msg.reasoning_content = reasoning + if (calls.length) msg.tool_calls = calls + r.delivered?.() + return Response.json({ id: cid, object: "chat.completion", created, model, choices: [{ index: 0, message: msg, finish_reason: stop }], ...(usage ? { usage } : {}) }, { headers: responseHeaders }) } - if (reasoning) msg.reasoning_content = reasoning - if (calls.length) msg.tool_calls = calls - return Response.json({ id: cid, object: "chat.completion", created, model, choices: [{ index: 0, message: msg, finish_reason: stop }], ...(usage ? { usage } : {}) }) } const chunk = (delta, finish_reason = null, extra = {}) => @@ -2326,16 +2660,17 @@ async function answerOf(auth, chat, signal, session = "") { let began = false const stream = new ReadableStream({ async pull(ctl) { - const r = await it.next() + const next = await events.next() if (!began) { began = true ctl.enqueue(chunk({ role: "assistant", content: "" })) } - if (r.done) { + if (next.done) { + r.delivered?.() ctl.enqueue(enc.encode("data: [DONE]\n\n")) return ctl.close() } - const e = r.value + const e = next.value if (e.text) ctl.enqueue(chunk({ content: e.text })) else if (e.reasoning) ctl.enqueue(chunk({ reasoning_content: e.reasoning })) else if (e.tool) ctl.enqueue(chunk({ tool_calls: [{ index: e.tool.index, id: e.tool.id, type: "function", function: { name: e.tool.name, arguments: e.tool.args } }] })) @@ -2345,11 +2680,12 @@ async function answerOf(auth, chat, signal, session = "") { ctl.close() } }, - cancel() { - it.return?.() + async cancel() { + await r.cancel?.() + await events.return() }, }) - return new Response(stream, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } }) + return new Response(stream, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", ...responseHeaders } }) } // ---- the plugin --------------------------------------------------------------------------- @@ -2446,4 +2782,4 @@ export async function CursorAuthPlugin() { } // for tests -export const _internal = { onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } +export const _internal = { nativeTransport, onDemandOf,resetH1: () => (h1Until = 0), onH1: () => Date.now() < h1Until, H2, H1, h2Blocked, open, openH1, openH2, STEP_WAIT, stepUsage, usageKey, ledger, owed, flights, misses, unreadable, catalog, usable, request, modelsOf, tokensOf, maxRequired, conversationID, usageOf, sessionOf, SESSION, errorResponse, kept, poolBase, conversation, buildRun, decode, exec, fields, pb, pbValue, pbAny, frame, frames, failure, toolsOf, expiry } diff --git a/packages/cursor/latency.test.mjs b/packages/cursor/latency.test.mjs index 57a93f8..726c29f 100644 --- a/packages/cursor/latency.test.mjs +++ b/packages/cursor/latency.test.mjs @@ -11,6 +11,7 @@ import "./nonet.mjs" // first: no request leaves this machine import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test" import http2 from "node:http2" import { CursorAuthPlugin, _internal } from "./index.mjs" +import { NATIVE_LIMITS, nativeSessions } from "./native-session.mjs" const { fields, pb, frame, STEP_WAIT } = _internal @@ -22,7 +23,13 @@ const SHOWS = 4500 / SCALE const real = globalThis.fetch const wait = { ...STEP_WAIT } -beforeEach(() => { +const retained = NATIVE_LIMITS.perProcess +beforeEach(async () => { + await nativeSessions.clear() + // This server closes each tool Run to publish dashboard usage. Exercise the + // production stateless fallback explicitly; native same-Run totals have + // separate roundtrip coverage in native-e2e/native-http1. + NATIVE_LIMITS.perProcess = 0 // the times, not the counts; a debt is let go as before for (const k of ["first", "every", "until", "ask", "owedAt"]) if (k in wait) STEP_WAIT[k] = wait[k] / SCALE _internal.owed?.clear() @@ -30,6 +37,7 @@ beforeEach(() => { _internal.unreadable?.clear() }) afterEach(() => { + NATIVE_LIMITS.perProcess = retained globalThis.fetch = real Object.assign(STEP_WAIT, wait) }) diff --git a/packages/cursor/native-e2e.test.mjs b/packages/cursor/native-e2e.test.mjs new file mode 100644 index 0000000..2931fb7 --- /dev/null +++ b/packages/cursor/native-e2e.test.mjs @@ -0,0 +1,1387 @@ +import "./nonet.mjs" +import { afterEach, beforeEach, expect, test } from "bun:test" +import http2 from "node:http2" +import { randomUUID } from "node:crypto" +import { getEventListeners } from "node:events" +import { CursorAuthPlugin, _internal } from "./index.mjs" +import { NATIVE_LIMITS, nativeSessions } from "./native-session.mjs" +import { message, bin, text, uint, readWire, nest, number, string, envelope, update, end, tool, setBlob, getBlob, checkpoint, abortExec, readResult } from "./native-test-wire.mjs" + +const savedFetch = globalThis.fetch +const limits = { ...NATIVE_LIMITS } +const usageWait = { ..._internal.STEP_WAIT } +const agents = [] +beforeEach(async () => { + await nativeSessions.clear() + _internal.resetH1() + Object.assign(_internal.STEP_WAIT, { first: 0, every: 5, until: 40, ask: 250, owedAt: 1000 }) +}) +afterEach(async () => { + await nativeSessions.clear() + for (const a of agents.splice(0)) { + for (const timer of a.timers) clearTimeout(timer) + for (const s of a.sessions) s.destroy() + await new Promise((r) => a.server.close(r)) + } + globalThis.fetch = savedFetch + for (const key of Object.keys(NATIVE_LIMITS)) if (!(key in limits)) delete NATIVE_LIMITS[key] + Object.assign(NATIVE_LIMITS, limits) + Object.assign(_internal.STEP_WAIT, usageWait) + for (const map of [_internal.owed, _internal.flights, _internal.misses, _internal.unreadable]) map.clear() +}) +const until = async (predicate) => { + const deadline = Date.now() + 1200 + while (!predicate()) { + if (Date.now() >= deadline) throw new Error("fixture did not reach its expected state") + await new Promise((r) => setTimeout(r, 5)) + } +} +const auth = () => ({ type: "oauth", access: `e30.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 7200, sub: "synthetic-" + randomUUID() })).toString("base64url")}.fixture`, refresh: "", accountId: "fixture@example.invalid" }) +const tools = [{ type: "function", function: { name: "audit_echo", description: "synthetic echo", parameters: { type: "object", properties: { value: { type: "string" } } } } }] +const initial = (extra = {}) => ({ model: "fixture-model", tools, messages: [{ role: "system", content: "synthetic instructions" }, { role: "user", content: "perform two synthetic calls" }], ...extra }) +const continueWith = (chat, reply, values) => ({ + ...chat, + messages: [...chat.messages, reply.choices[0].message, ...reply.choices[0].message.tool_calls.map((c, i) => ({ role: "tool", tool_call_id: c.id, content: values[i] }))], +}) +const choice = (response) => response.body.choices[0] + +// The fake only advances on an independently decoded native McpResult followed +// by the numeric exec close. Replaying a Chat transcript in a fresh Run cannot +// make the second call or final answer succeed. +async function agent(options = {}) { + const firstID = options.omitZeroID ? 0 : 7 + const a = { histories: [], runs: [], started: [], events: [], dashboardRequests: [], results: [], closes: [], unavailable: [], kv: [], errors: [], sessions: new Set(), timers: [], closedStreams: 0 } + a.server = http2.createServer() + a.server.on("session", (s) => { a.sessions.add(s); s.on("error", () => {}); s.on("close", () => a.sessions.delete(s)) }) + a.server.on("stream", (stream) => { + stream.on("error", () => {}) + stream.on("close", () => a.closedStreams++) + stream.respond({ ":status": 200, "content-type": "application/connect+proto" }) + let buffer = Buffer.alloc(0) + let began = false + let phase = 0 + const received = new Map() + const closed = new Set() + let marker = "" + let imported = [], bootstrap = new Map() + const send = (b) => { if (!stream.destroyed && !stream.closed) stream.write(b) } + a.push = send + const delay = (fn, ms = 20) => a.timers.push(setTimeout(() => { if (!stream.destroyed && !stream.closed) fn() }, ms)) + const state = (pending, terminal = false) => { + const root = Buffer.from("fixture-root") + const user = Buffer.from("fixture-user") + const thinking = Buffer.from("fixture-thinking-" + phase) + const turn = Buffer.from("fixture-turn") + const callID = "call_a\nfc_b" + const step = bin(3, message(text(1, "server-generated thinking phase " + phase), uint(2, 11))) + const stepRefs = [thinking] + const extras = [] + if (terminal) { + const call = Buffer.from("fixture-tool-step") + const final = Buffer.from("fixture-answer-step") + const nativeArgs = message(text(1, "magpie-audit_echo"), text(3, callID), text(4, "magpie"), text(5, "audit_echo")) + const success = bin(1, bin(1, bin(1, text(1, marker)))) + extras.push([call, bin(2, bin(15, message(bin(1, nativeArgs), bin(2, success))))], [final, bin(1, text(1, marker))]) + stepRefs.push(call, final) + } + const turnBytes = bin(1, message(bin(1, user), ...stepRefs.map((id) => bin(2, id)))) + const stateBytes = message(bin(1, root), bin(8, turn), ...(pending ? [text(4, callID)] : []), uint(10, 1), text(22, "cli")) + send(checkpoint(stateBytes)) // a candidate before its reference closure + delay(() => { + const blobs = [[root, Buffer.from('{"role":"system","content":"synthetic root"}')], [user, text(1, "synthetic input")], [thinking, step], ...extras, [turn, turnBytes]] + for (const [i, [id, b]] of blobs.entries()) send(setBlob(100 + phase * 10 + i, id, b)) + send(getBlob(199 + phase * 10, thinking)) + }, options.stateDelay ?? 20) + } + const first = () => { + if (options.stallInitial) return + send(update(4, text(1, options.initialReasoning ?? "native planning one"))) + if (options.toolDisplay) { + const at = Math.floor(options.toolDisplay.length / 2) + send(update(1, text(1, options.toolDisplay.slice(0, at)))) + send(update(1, text(1, options.toolDisplay.slice(at)))) + } + if (options.unsupportedExec) { send(envelope(bin(2, message(uint(1, 77), bin(12, text(1, "synthetic shell request")))))); return } + if (options.thinkingOnly) return + if (options.progressiveFinal || options.finalOnly) { + send(update(1, text(1, "progressive answer"))) + a.finish = () => { + send(update(14, message(uint(1, 23), uint(2, 7), uint(3, 10), uint(4, 0)))) + stream.end(end()) + } + if (options.finalOnly) a.finish() + return + } + const count = options.parallel || options.truncated ? 2 : 1 + const listed = () => { if (!options.noCount && !options.cleanNoCount) send(update(27, uint(1, count))) } + if (!options.countAfter) listed() + const c = options.execMessage ? envelope(bin(2, options.execMessage)) : tool(firstID, "call_a\nfc_b", "seed", { ...options, omitID: options.omitZeroID }) + if (options.changedDuplicate || options.extraExec) { + const extra = options.changedDuplicate ? tool(firstID, "call_a\nfc_b", "changed") : tool(9, "new-exec-after-seal", "unexpected") + send(envelope(message(c.subarray(5), extra.subarray(5)))) + } else send(c) + if (options.duplicate) send(c) + if (options.parallel) { + const last = tool(8, "call_a__fc_b", "other") + send(last) + if (options.duplicateFinal) send(last) + } + if (options.countAfter) listed() + if (options.truncated || options.cleanNoCount) return stream.end(end()) + state(true) + if (options.serverAbort) delay(() => send(abortExec(7)), 35) + } + const advance = () => { + const expected = phase === 0 && options.parallel ? [firstID, 8] : [phase === 0 ? firstID : 8] + if (!expected.every((id) => closed.has(id))) return + if (phase === 0 && !options.parallel && !options.finalAfterFirst) { + marker = received.get(firstID).content[0].text + phase = 1 + send(update(4, text(1, "native planning two"))) + send(tool(8, "call_a__fc_b", marker, { name: options.name })) // call-before-count in phase two + if (!options.secondNoCount) send(update(27, uint(1, 1))) + state(true) + return + } + 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 + send(update(4, text(1, "native final thinking"))) + send(update(1, text(1, marker))) + const usage = 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)) + send(update(14, usage)) + state(false, true) // late state after TurnEnded must still be retained + if (!options.noEnd) delay(() => stream.end(end()), 55) + } + stream.on("data", (chunk) => { + buffer = Buffer.concat([buffer, chunk]) + try { + while (buffer.length >= 5 && buffer.length >= 5 + buffer.readUInt32BE(1)) { + const n = buffer.readUInt32BE(1) + const b = buffer.subarray(5, 5 + n) + buffer = buffer.subarray(5 + n) + const fs = readWire(b) + if (fs.some((f) => f.no === 1)) { + if (began) throw new Error("more than one RunRequest on retained transport") + began = true + const run = nest(b, 1) + a.runs.push(run) + a.started.push(Date.now()) + options.onRun?.(a) + a.histories.push(imported) + const refs = readWire(nest(run, 1)).filter((f) => f.no === 1) + bootstrap = new Map(refs.map((f, i) => [1000 + i, i])) + for (const [i, ref] of refs.entries()) send(getBlob(1000 + i, ref.data)) + if (!refs.length) first() + } else if (fs.some((f) => f.no === 2)) { + const r = readResult(b) + if (received.has(r.id)) throw new Error("duplicate native result submission") + if (r.execID !== "exec-" + r.id || r.content[0]?.type !== "text") throw new Error("incorrect native result routing/content") + received.set(r.id, r) + a.results.push(r) + } else if (fs.some((f) => f.no === 5)) { + const control = nest(b, 5) + const close = readWire(control).find((f) => f.no === 1) + if (!close) { + if (readWire(control).some((f) => f.no === 2)) a.unavailable.push(control) + continue + } + const id = number(close.data, 1) + if (options.unsupportedExec && id === 77 || (options.name === "unregistered" || options.provider === "foreign" || options.approval) && id === firstID) { + send(update(1, text(1, "continued after unavailable"))) + send(update(14, message(uint(1, 5), uint(2, 3)))) + stream.end(end()) + continue + } + if (!received.has(id)) throw new Error("exec close arrived before McpResult") + if (closed.has(id)) throw new Error("duplicate exec close") + closed.add(id) + a.closes.push(id) + advance() + } else if (fs.some((f) => f.no === 3)) { + const kv = nest(b, 3) + const id = number(kv, 1) + a.kv.push({ id, fields: readWire(kv) }) + if (bootstrap.has(id)) { + imported[bootstrap.get(id)] = JSON.parse(nest(nest(kv, 2), 1).toString()) + bootstrap.delete(id) + if (!bootstrap.size) { + if ((options.toolRuns ?? [1]).includes(a.runs.length)) first() + else { + const results = imported.filter((m) => m.role === "tool").flatMap((m) => m.content) + const marker = results.flatMap((r) => r.experimental_content ?? r.result?.value?.content ?? []).map((r) => r.text ?? r.content?.value?.text ?? "").join("|") + send(update(1, text(1, "rebuilt:" + (marker || "new-input")))) + send(update(14, options.rebuildUsage ?? message(uint(1, 13), uint(2, 4)))) + stream.end(end()) + } + } + } + } + } + } catch (e) { + a.errors.push(e.message) + if (!stream.destroyed) stream.end(envelope(Buffer.from(JSON.stringify({ error: { code: "invalid_argument", message: e.message } })), 2)) + } + }) + }) + await new Promise((r) => a.server.listen(0, "127.0.0.1", r)) + a.base = `http://127.0.0.1:${a.server.address().port}` + agents.push(a) + globalThis.fetch = async (url, init) => { + const u = String(url) + if (u.endsWith("/aiserver.v1.ServerConfigService/GetServerConfig")) return Response.json({ agentUrlConfig: { agentUrl: a.base } }) + if (u.endsWith("/agent.v1.AgentService/GetUsableModels")) return Response.json({ models: [{ modelId: "fixture-model", displayName: "Synthetic" }] }) + if (u.endsWith("/aiserver.v1.AiService/AvailableModels") && options.picker) return Response.json({ models: options.picker }) + if (u.endsWith("/aiserver.v1.DashboardService/GetFilteredUsageEvents")) { + a.dashboardRequests.push({ account: init.headers.Authorization, at: Date.now(), closed: a.closedStreams }) + return options.dashboard ? await options.dashboard(a, init) : Response.json({ usageEventsDisplay: a.events }) + } + throw new Error("unexpected fake API request: " + u) + } + a.firstID = firstID + a.ask = async (account, chat, { signal, session = "fixture-session" } = {}) => { + const plugin = await CursorAuthPlugin() + const loader = await plugin.auth.loader(async () => account) + const res = await loader.fetch(a.base + "/v1/chat/completions", { method: "POST", headers: { "x-magpie-cursor-session": session }, body: JSON.stringify(chat), signal }) + if (chat.stream) return res + return { status: res.status, body: await res.json(), diagnostic: res.headers.get("X-Magpie-Cursor-Continuity") } + } + return a +} + +// A fresh Run must obtain already provided client results from bootstrap blobs. +// The marker is never inferred from Chat requests or from native result writes. +const rebuilt = (response, marker) => { + expect(response.status).toBe(200) + expect(choice(response).message.content).toContain("rebuilt:" + marker) + expect(response.diagnostic).toMatch(/^stateless;/) +} + +test("native retention: healthy two external roundtrips use one Run", async () => { + const a = await agent(), account = auth(), chat = initial() + const first = await a.ask(account, chat) + expect(first.status).toBe(200) + const marker = "synthetic-" + randomUUID() + "\n精确结果" + const next = continueWith(chat, first.body, [marker]) + const second = await a.ask(account, next) + expect(second.status).toBe(200) + expect(JSON.parse(choice(second).message.tool_calls[0].function.arguments)).toEqual({ value: marker }) + const final = await a.ask(account, continueWith(next, second.body, [marker])) + expect(final.status).toBe(200) + expect(choice(final).message.content).toBe(marker) + expect(final.body.usage).toMatchObject({ prompt_tokens: 23, completion_tokens: 7, total_tokens: 30 }) + expect(a.runs).toHaveLength(1) + expect(a.results.map((r) => r.id)).toEqual([7, 8]) + expect(a.closes).toEqual([7, 8]) + expect(a.errors).toEqual([]) +}) + +test("native retention: Task parent awaiting results permits a child sharing session with different first user", async () => { + const a = await agent({ name: "Task" }), account = auth(), parent = initial({ tools: [{ type: "function", function: { name: "Task", parameters: { type: "object" } } }] }) + const first = await a.ask(account, parent) + expect(first.status).toBe(200) + const owner = [...nativeSessions.entries][0] + const child = initial({ messages: [{ role: "user", content: "child task with separate first user" }] }) + const response = await a.ask(account, child) + expect(response.status).toBe(200) + expect(a.runs).toHaveLength(2) + expect(string(a.runs[0], 5)).not.toBe(string(a.runs[1], 5)) + expect(owner.state).toBe("awaiting-results") + expect(owner.error).toBeUndefined() + const continued = await a.ask(account, continueWith(parent, first.body, ["child finished"])) + expect(continued.status).toBe(200) + expect(a.results).toHaveLength(1) + expect(a.runs).toHaveLength(2) +}) + +for (const limit of ["resultWait", "lifetime"]) test(`native retention: ${limit} expiry rebuilds supplied results on a fresh stateless Run`, async () => { + NATIVE_LIMITS[limit] = 65 + 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] + await until(() => owner.state === "expired") + const marker = "late-result-" + limit + rebuilt(await a.ask(account, continueWith(chat, first.body, [marker])), marker) + expect(a.runs).toHaveLength(2) + expect(a.results).toEqual([]) + expect(a.errors).toEqual([]) +}) + +for (const loss of ["clear", "restart"]) test(`native retention: process ${loss} rebuilds history without the former owner`, async () => { + const a = await agent(), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["process-" + loss]) + const owner = [...nativeSessions.entries][0] + await nativeSessions.clear() + if (loss === "restart") { + // Synthetic process replacement loses every ownership map, without loading + // another process's configuration or requiring native history validation. + nativeSessions.entries.clear(); nativeSessions.handles.clear(); nativeSessions.selectors.clear() + next.messages.at(-2).content = "caller retained only its display transcript" + } + rebuilt(await a.ask(account, next), "process-" + loss) + expect(owner.state).toBe("cancelled") + expect(a.runs).toHaveLength(2) + expect(a.results).toEqual([]) +}) + +test("native retention: cross-account continuation rebuilds history without writing to the original account", async () => { + const a = await agent(), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const owner = [...nativeSessions.entries][0] + rebuilt(await a.ask(auth(), continueWith(chat, first.body, ["different-account"])), "different-account") + expect(a.runs).toHaveLength(2) + expect(a.results).toEqual([]) + expect(owner.state).toBe("awaiting-results") +}) + +for (const kind of ["same first user", "different tools", "pending ancestor", "new input"]) test(`native retention: busy owner with ${kind} falls back without cancelling its live parent`, async () => { + const a = await agent(), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const owner = [...nativeSessions.entries][0] + let branch = structuredClone(chat) + let marker = "new-input" + if (kind === "different tools") branch.tools[0].function.description = "child-specific tools" + if (kind === "pending ancestor") { + branch.messages.push(choice(first).message, { role: "user", content: "child request includes a pending parent Task" }) + marker = "Tool use was interrupted and did not produce a result." + } + if (kind === "new input") { branch = continueWith(chat, first.body, ["already-provided"]); branch.messages.push({ role: "user", content: "branch on new input" }); marker = "already-provided" } + rebuilt(await a.ask(account, branch), marker) + expect(owner.state).toBe("awaiting-results") + expect(owner.error).toBeUndefined() + expect(owner.transportClosed).not.toBe(true) + expect(a.results).toEqual([]) + expect(a.runs).toHaveLength(2) + const second = await a.ask(account, continueWith(chat, first.body, ["parent result"])) + expect(second.status).toBe(200) + expect(a.results).toHaveLength(1) + expect(a.runs).toHaveLength(2) +}) + +for (const bound of ["perAccount", "perProcess"]) test(`native retention: ${bound} capacity selects production stateless fallback`, async () => { + NATIVE_LIMITS[bound] = 1 + 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] + rebuilt(await a.ask(account, initial({ messages: [{ role: "user", content: "independent capacity request" }] }), { session: "second-session" }), "new-input") + expect(a.runs).toHaveLength(2) + expect(nativeSessions.entries.size).toBe(1) + expect(owner.state).toBe("awaiting-results") +}) + +for (const change of ["model", "reasoning_effort", "tools", "metadata", "history", "assistant output", "missing parallel result", "unsupported result"]) test(`native retention: incompatible ${change} rebuilds history instead of enforcing native matching`, async () => { + const a = await agent({ parallel: change === "missing parallel result" }), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["compatible-history", "second-result"]) + if (change === "model") next.model = "different-model" + if (change === "reasoning_effort") next.reasoning_effort = "high" + if (change === "tools") next.tools = [] + if (change === "metadata") next.metadata = { synthetic: "new trace" } + if (change === "history") next.messages[0].content = "changed instructions" + if (change === "assistant output") next.messages.at(-2).content = "different display text" + if (change === "missing parallel result") next.messages.pop() + if (change === "unsupported result") next.messages.at(-1).content = [{ type: "file", file: { filename: "opaque.txt" } }, { type: "text", text: "compatible-history" }] + rebuilt(await a.ask(account, next), "compatible-history") + expect(a.results).toEqual([]) + expect(a.runs).toHaveLength(2) +}) + +test("native retention: terminal old handles do not wedge a new user turn", async () => { + const a = await agent({ finalAfterFirst: true }), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["finished-tool"]) + const final = await a.ask(account, next) + expect(final.status).toBe(200) + next.messages.push(choice(final).message, { role: "user", content: "new turn after terminal owner" }) + rebuilt(await a.ask(account, next), "finished-tool") + expect(a.runs).toHaveLength(2) + expect(a.results).toHaveLength(1) +}) + +test("native retention: unknown exec is refused and the model continues", async () => { + const a = await agent({ unsupportedExec: true }) + const result = await a.ask(auth(), initial()) + expect(result.status).toBe(200) + expect(choice(result).message.content).toBe("continued after unavailable") + expect(a.unavailable).toHaveLength(1) + expect(a.results).toEqual([]) +}) + +test("native retention: baseline unknown fields and stop remain compatible", async () => { + const a = await agent({ finalOnly: true }) + const result = await a.ask(auth(), initial({ stop: "END", caller_metadata: { synthetic: true } })) + expect(result.status).toBe(200) + expect(a.runs).toHaveLength(1) +}) + +for (const effort of ["none", "off"]) test(`native retention: ${effort} without a served off variant uses legacy thinking=false`, async () => { + const variant = { legacySlug: "synthetic-thinking-high", parameterValues: [{ id: "context", value: "200k" }, { id: "thinking", value: "true" }, { id: "effort", value: "high" }], isDefaultNonMaxConfig: true } + const picker = [{ name: "synthetic-thinking", supportsNonMaxMode: true, parameterDefinitions: [ + { id: "context", parameterType: { enumParameter: { values: [{ value: "200k" }] } } }, + { id: "thinking", parameterType: { booleanParameter: { values: [{ value: "true" }, { value: "false" }] } } }, + { id: "effort", parameterType: { enumParameter: { values: [{ value: "low" }, { value: "high" }] } } }, + ], variants: [variant] }] + const a = await agent({ picker, finalOnly: true }) + const result = await a.ask(auth(), initial({ model: "synthetic-thinking@200k", reasoning_effort: effort })) + expect(result.status).toBe(200) + const params = readWire(nest(a.runs[0], 9)).filter((f) => f.no === 3).map((f) => [string(f.data, 1), string(f.data, 2)]) + expect(Object.fromEntries(params).thinking).toBe("false") +}) + +async function twoRounds(a, account, chat = initial(), options) { + const first = await a.ask(account, chat, options) + expect(first.status).toBe(200) + expect(choice(first).finish_reason).toBe("tool_calls") + const firstRuns = a.runs.length + const marker = "synthetic-" + randomUUID() + "\n精确结果" + const secondChat = continueWith(chat, first.body, [marker]) + const second = await a.ask(account, secondChat) + expect(second.status).toBe(200) + expect(choice(second).finish_reason).toBe("tool_calls") + expect(JSON.parse(choice(second).message.tool_calls[0].function.arguments)).toEqual({ value: marker }) + const secondRuns = a.runs.length + const finalChat = continueWith(secondChat, second.body, [marker]) + const final = await a.ask(account, finalChat) + expect(final.status).toBe(200) + expect(choice(final).finish_reason).toBe("stop") + expect(choice(final).message.content).toBe(marker) + expect(choice(final).message.tool_calls).toBeUndefined() + expect(a.runs).toHaveLength(1) + expect([firstRuns, secondRuns - firstRuns, a.runs.length - secondRuns]).toEqual([1, 0, 0]) + expect(a.results.map((r) => r.id)).toEqual([a.firstID, 8]) + expect(a.closes).toEqual([a.firstID, 8]) + expect(a.results.every((r) => r.content[0].text === marker)).toBe(true) + expect(a.errors).toEqual([]) + return { first, second, final, finalChat, secondChat, marker } +} + +// Generated offline by Cursor CLI 2026.08.11-e8db854's actual +// ExecServerMessage serializer with id=0; it omits nonoptional scalar field 1. +const ZERO_EXEC = Buffer.from("5a370a116d61677069652d61756469745f6563686f1a0e73796e7468657469632d63616c6c22066d61677069652a0a61756469745f6563686f7a1373796e7468657469632d657865632d7a65726f", "hex") + +test("native exec: actual descriptor golden omits id=0 and routes to numeric zero", () => { + expect(readWire(ZERO_EXEC).some((f) => f.no === 1)).toBe(false) + const call = _internal.exec(ZERO_EXEC, [{ name: "audit_echo" }], () => { throw new Error("unexpected native write") }, () => {}, null, true) + expect(call).toMatchObject({ requestID: 0, execID: "synthetic-exec-zero", nativeID: "synthetic-call", name: "audit_echo", args: "{}" }) +}) + +test("native exec: malformed explicit id is rejected instead of defaulting to zero", () => { + for (const id of [bin(1, Buffer.from([0])), uint(1, 2 ** 32)]) { + expect(() => _internal.exec(message(id, ZERO_EXEC), [{ name: "audit_echo" }], () => {}, () => {}, null, true)).toThrow("invalid native exec request ID") + } +}) + +test("native HTTP/2: omitted-zero exec ID survives two result roundtrips on one Run", async () => { + const a = await agent({ omitZeroID: true }) + const { final } = await twoRounds(a, auth()) + expect(final.body.usage.prompt_tokens_details).toEqual({ cached_tokens: 10, cache_write_tokens: 0 }) + expect(a.results[0].execID).toBe("exec-0") +}) + + +test("native loader: real matched tool result preserves text/image/text and isError on the same exec", async () => { + const a = await agent() + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + const png = Buffer.from("89504e470d0a1a0a", "hex") + const next = continueWith(chat, first.body, [[{ type: "text", text: "before" }, { type: "image_url", image_url: { url: "data:image/png;base64," + png.toString("base64") } }, { type: "text", text: "after" }]]) + next.messages.at(-1).isError = true + const second = await a.ask(account, next) + expect(second.status).toBe(200) + expect(a.results[0]).toEqual({ id: 7, execID: "exec-7", isError: true, content: [ + { type: "text", text: "before" }, { type: "image", data: png, mimeType: "image/png" }, { type: "text", text: "after" }, + ] }) + expect(a.runs).toHaveLength(1) +}) + + +for (const representation of ["empty-array", "text-parts", "reasoning-parts", "split-pieces"]) test(`native loader: canonical assistant ${representation} matches current output and accepted history`, async () => { + const a = await agent({ toolDisplay: representation === "empty-array" ? "" : "First piece.Second piece." }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["canonical display"]) + const assistant = next.messages.at(-2) + const text = assistant.content, reasoning = assistant.reasoning_content + if (representation === "empty-array") assistant.content = [] + else if (representation === "text-parts") assistant.content = [{ type: "text", text: text.slice(0, 5) }, { type: "text", text: text.slice(5) }] + else if (representation === "reasoning-parts") { + assistant.content = [{ type: "reasoning", text: reasoning }, { type: "text", text }] + delete assistant.reasoning_content + } else { + next.messages.splice(-2, 1, + { role: "assistant", content: text.slice(0, 5), reasoning_content: reasoning.slice(0, 5) }, + { ...assistant, content: text.slice(5), reasoning_content: reasoning.slice(5) }) + } + const changed = structuredClone(next) + changed.messages.at(-2).content = [{ type: "text", text: text + "changed" }] + rebuilt(await a.ask(account, changed), "canonical display") + expect(a.results).toEqual([]) + const second = await a.ask(account, next) + expect(second.status).toBe(200) + const finalChat = continueWith(next, second.body, ["canonical display"]) + if (representation === "split-pieces") { + for (const m of finalChat.messages.slice(chat.messages.length, chat.messages.length + 2)) m.content = [{ type: "text", text: m.content }] + } else finalChat.messages[chat.messages.length] = choice(first).message + const final = await a.ask(account, finalChat) + expect(final.status).toBe(200) + expect(a.runs).toHaveLength(2) + expect(a.results.map((r) => r.id)).toEqual([7, 8]) +}) + + +test("native loader: streamed ordinary text/thinking arrives before the server permits completion", async () => { + const a = await agent({ progressiveFinal: true }) + let timer + const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("progressive output waited for completion")), 1000) }) + try { + const response = await Promise.race([a.ask(auth(), initial({ stream: true })), timeout]) + expect(response.status).toBe(200) + const reader = response.body.getReader() + let sse = "" + while (!sse.includes("progressive answer")) sse += new TextDecoder().decode((await Promise.race([reader.read(), timeout])).value) + expect(sse).toContain("native planning one") + expect(sse).not.toContain("[DONE]") + expect([...nativeSessions.entries][0].terminal).toBe(false) + a.finish() + while (true) { + const item = await reader.read() + if (item.done) break + sse += new TextDecoder().decode(item.value) + } + expect(sse).toContain("[DONE]") + expect(response.headers.get("X-Magpie-Cursor-Continuity")).toContain("same-run") + } finally { clearTimeout(timer) } +}) + + +for (const bound of ["bytes", "messages"]) test(`native loader HTTP/2: stalled writes bound queued parked KV ${bound}`, async () => { + NATIVE_LIMITS.outboundBytes = 4 << 20 + NATIVE_LIMITS.outboundMessages = bound === "messages" ? 4 : 256 + const a = await agent({ stateDelay: 10_000 }) + const connect = http2.connect + let req + http2.connect = (...args) => { + const session = connect(...args) + const request = session.request + session.request = function (...args) { req = request.apply(this, args); return req } + return session + } + try { + const first = await a.ask(auth(), initial()) + expect(first.status).toBe(200) + const owner = [...nativeSessions.entries][0] + const blobID = Buffer.from("synthetic-h2-queued-blob") + a.push(setBlob(90, blobID, Buffer.alloc(bound === "bytes" ? 1 << 20 : 1))) + await until(() => a.kv.some((k) => k.id === 90)) + const stalledWrites = [] + req.write = (chunk) => { stalledWrites.push(chunk); return false } + for (let i = 0; i < 10; i++) a.push(getBlob(91 + i, blobID)) + await until(() => !!owner.error) + expect(owner.error.status).toBe(503) + expect(owner.error.message).toContain("outbound") + expect(owner.error.message).toContain(bound) + expect(stalledWrites).toHaveLength(1) + expect(owner.transport.outbound).toEqual({ bytes: 0, messages: 0 }) + await until(() => a.closedStreams === 1) + expect(a.results).toEqual([]) + expect(a.runs).toHaveLength(1) + } finally { http2.connect = connect } +}) + + +test("native loader HTTP/2: write callback alone does not bypass false-write backpressure; drain preserves the result loop", async () => { + const a = await agent({ stateDelay: 10_000 }) + const connect = http2.connect + let req + http2.connect = (...args) => { + const session = connect(...args) + const request = session.request + session.request = function (...args) { req = request.apply(this, args); return req } + return session + } + try { + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + const write = req.write + const writes = [] + req.write = (chunk, callback) => { writes.push(chunk); queueMicrotask(() => callback?.()); return false } + a.push(getBlob(90, Buffer.from("missing-a"))) + a.push(getBlob(91, Buffer.from("missing-b"))) + await until(() => writes.length > 0) + await new Promise((r) => setTimeout(r, 15)) + expect(writes).toHaveLength(1) + req.emit("drain") + await until(() => writes.length === 2) + req.write = write + req.emit("drain") + const secondChat = continueWith(chat, first.body, ["after drain"]) + const second = await a.ask(account, secondChat) + const final = await a.ask(account, continueWith(secondChat, second.body, ["after drain"])) + expect(final.status).toBe(200) + expect(a.results.map((r) => r.id)).toEqual([7, 8]) + expect(a.closes).toEqual([7, 8]) + expect(a.runs).toHaveLength(1) + } finally { http2.connect = connect } +}) + +test("native HTTP/2: background reader retains/ACKs late blobs and closes checkpoint references while parked", async () => { + const a = await agent({ stateDelay: 60 }) + const first = await a.ask(auth(), initial()) + expect(first.status).toBe(200) + const owner = [...nativeSessions.entries][0] + expect(owner.checkpoint.status).toBe("incomplete") + await until(() => a.kv.some((k) => k.id === 199)) + expect(owner.state).toBe("awaiting-results") + expect(owner.checkpoint.status).toBe("complete") + const response = a.kv.find((k) => k.id === 199).fields.find((f) => f.no === 2).data + expect(nest(response, 1)).toEqual(owner.blobs.get(Buffer.from("fixture-thinking-0").toString("hex"))) + expect(a.closedStreams).toBe(0) +}) + +for (const countAfter of [false, true]) test(`native HTTP/2: parallel calls count ${countAfter ? "after" : "before"}, colliding raw IDs, reverse results, exactly one submission`, async () => { + const a = await agent({ parallel: true, countAfter, duplicate: true }) + const account = auth() + const chat = initial() + const first = await a.ask(account, chat) + expect(first.status).toBe(200) + const calls = choice(first).message.tool_calls + expect(calls).toHaveLength(2) + expect(new Set(calls.map((c) => c.id)).size).toBe(2) + const continuation = continueWith(chat, first.body, ["result-7", "result-8"]) + continuation.messages.splice(-2, 2, ...continuation.messages.slice(-2).reverse()) + const final = await a.ask(account, continuation) + expect(final.status).toBe(200) + expect(choice(final).message.content).toBe("result-7|result-8") + const replay = await a.ask(account, continuation) + expect(choice(replay).message.content).toBe(choice(final).message.content) + expect(replay.body.usage.magpie_native.accounting).toBe("replayed") + expect(replay.body.usage.total_tokens).toBe(0) + expect(a.results.map((r) => r.id).sort()).toEqual([7, 8]) + expect(a.runs).toHaveLength(1) + expect(a.errors).toEqual([]) +}) + + +for (const cancelBody of [true, false]) test(`native loader: cancelling a cached streamed replay ${cancelBody ? "through its body" : "through its request signal"} preserves the active owner`, async () => { + const a = await agent() + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + const secondChat = continueWith(chat, first.body, ["replay-safe"]) + const second = await a.ask(account, secondChat) + const owner = [...nativeSessions.entries][0] + const handles = [...nativeSessions.handles.keys()] + const ac = new AbortController() + const replay = await a.ask(account, { ...secondChat, stream: true }, { signal: ac.signal }) + expect(replay.status).toBe(200) + if (cancelBody) await replay.body.cancel() + else { ac.abort(); await replay.body.cancel() } + expect(owner.state).toBe("awaiting-results") + expect(owner.error).toBeUndefined() + expect(owner.transportClosed).not.toBe(true) + expect([...nativeSessions.handles.keys()]).toEqual(handles) + const final = await a.ask(account, continueWith(secondChat, second.body, ["replay-safe"])) + expect(final.status).toBe(200) + expect(choice(final).message.content).toBe("replay-safe") + expect(a.results.map((r) => r.id)).toEqual([7, 8]) + expect(a.runs).toHaveLength(1) +}) + +test("native loader: cancellation after the transport head but before bind closes the late transport", async () => { + const a = await agent({ stallInitial: true }) + const ac = new AbortController() + const connect = http2.connect + http2.connect = (...args) => { + const session = connect(...args) + const request = session.request + session.request = function (...args) { + const req = request.apply(this, args) + req.once("response", () => queueMicrotask(() => ac.abort())) + return req + } + return session + } + try { + const reply = await a.ask(auth(), initial(), { signal: ac.signal }) + expect(reply.status).toBe(410) + await until(() => a.closedStreams === 1 && a.sessions.size === 0) + expect(a.runs).toHaveLength(0) + expect(nativeSessions.entries.size).toBe(0) + expect(nativeSessions.handles.size).toBe(0) + } finally { http2.connect = connect } +}) + +test("native HTTP/2: allowed display-reasoning omission and argument key/whitespace equivalence retain the Run", async () => { + const a = await agent() + const account = auth() + const chat = initial() + const first = await a.ask(account, chat) + const continuation = continueWith(chat, first.body, ["equivalent"]) + const assistant = continuation.messages.at(-2) + delete assistant.reasoning_content + assistant.content = null + assistant.tool_calls[0].function.arguments = ' { "value" : "seed" } ' + const second = await a.ask(account, continuation) + expect(second.status).toBe(200) + expect(a.runs).toHaveLength(1) +}) + +test("native HTTP/2: a clean streamed handoff detaches the old signal; later abort does not kill its continuation", async () => { + const a = await agent() + const account = auth() + const ac = new AbortController() + const chat = initial({ stream: true }) + const res = await a.ask(account, chat, { signal: ac.signal }) + const sse = await res.text() + expect(sse).toContain("[DONE]") + expect(getEventListeners(ac.signal, "abort")).toHaveLength(0) + expect([...nativeSessions.entries][0].state).toBe("awaiting-results") + const chunks = sse.split("\n\n").filter((s) => s.startsWith("data: {")).map((s) => JSON.parse(s.slice(6))) + const toolCalls = chunks.flatMap((c) => c.choices?.[0]?.delta?.tool_calls ?? []).map(({ index, ...c }) => c) + const reasoning = chunks.map((c) => c.choices?.[0]?.delta?.reasoning_content ?? "").join("") + ac.abort() + const next = { ...chat, stream: false, messages: [...chat.messages, { role: "assistant", content: "", reasoning_content: reasoning, tool_calls: toolCalls }, { role: "tool", tool_call_id: toolCalls[0].id, content: "after-old-abort" }] } + expect((await a.ask(account, next)).status).toBe(200) + expect(a.results).toHaveLength(1) + expect(a.closedStreams).toBe(0) +}) + +for (const blocked of [false, true]) test(`native HTTP/2: streaming cancellation ${blocked ? "interrupts a blocked read" : "before reading"} settles transport/pump`, async () => { + const a = await agent({ thinkingOnly: true }) + const res = await a.ask(auth(), initial({ stream: true })) + const owner = [...nativeSessions.entries][0] + const before = Date.now() + if (blocked) { + const reader = res.body.getReader() + await reader.read() + await reader.read() + const pending = reader.read() + await reader.cancel() + await pending + } else await res.body.cancel() + await owner.pumpTask + await until(() => a.closedStreams === 1) + expect(Date.now() - before).toBeLessThan(1000) + expect(owner.state).toBe("cancelled") + expect(owner.transportClosed).toBe(true) +}) + +test("native loader: abort during metadata lookup leaves no opening owner or transport", async () => { + const a = await agent() + const ac = new AbortController() + const fetch = globalThis.fetch + globalThis.fetch = async (url, init) => { + const response = await fetch(url, init) + if (String(url).endsWith("/aiserver.v1.ServerConfigService/GetServerConfig")) ac.abort() + return response + } + const response = await a.ask(auth(), initial(), { signal: ac.signal }) + expect(response.status).toBe(410) + expect(a.runs).toHaveLength(0) + expect(a.sessions.size).toBe(0) + expect(nativeSessions.entries.size).toBe(0) + expect(nativeSessions.handles.size).toBe(0) +}) + +test("native HTTP/2: already-aborted request never opens Run; abort while awaiting initial output closes it", async () => { + const a = await agent({ stallInitial: true }) + const account = auth() + const ac = new AbortController() + ac.abort() + expect((await a.ask(account, initial(), { signal: ac.signal })).status).toBe(410) + expect(a.runs).toHaveLength(0) + const live = new AbortController() + const pending = a.ask(account, initial(), { signal: live.signal }) + await until(() => a.runs.length === 1) + live.abort() + expect((await pending).status).toBe(410) + await until(() => a.closedStreams === 1) +}) + +test("native HTTP/2: housekeeping cannot extend the result deadline; late supplied results rebuild history", async () => { + NATIVE_LIMITS.resultWait = 60 + const a = await agent() + const account = auth() + const chat = initial() + const first = await a.ask(account, chat) + const owner = [...nativeSessions.entries][0] + await until(() => owner.state === "expired") + // Housekeeping still arrives while parked; it cannot renew retention. The + // completed client result is safe imported data for the new stateless Run. + rebuilt(await a.ask(account, continueWith(chat, first.body, ["late"])), "late") + expect(a.results).toHaveLength(0) + expect(a.runs).toHaveLength(2) +}) + + +for (const options of [{ truncated: true }]) test(`native HTTP/2: ${options.truncated ? "truncated declared batch" : "missing batch count"} cannot yield successful partial calls`, async () => { + NATIVE_LIMITS.batchWait = 55 + const a = await agent(options) + const r = await a.ask(auth(), initial()) + expect(r.status).toBe(502) + expect(r.body.choices).toBeUndefined() + expect(a.results).toHaveLength(0) +}) + + +const protobufDouble = (value) => { + const data = Buffer.alloc(8) + data.writeDoubleLE(value) + return message(Buffer.from([0x11]), data) +} +const MALFORMED_VALUES = [ + ["truncated string", Buffer.from("1a0561", "hex")], + ["dangling tail", Buffer.from("1a017880", "hex")], + ["nested struct tail", bin(5, bin(1, message(text(1, "nested"), bin(2, Buffer.from("1a017880", "hex")))))], + ["nested list truncation", bin(6, bin(1, Buffer.from("1a0561", "hex")))], + ["wrong string wire", uint(3, 1)], + ["wrong number wire", uint(2, 1)], + ["wrong boolean wire", bin(4, Buffer.alloc(0))], + ["wrong struct wire", uint(5, 0)], + ["wrong list wire", uint(6, 0)], + ["wrong struct entry wire", bin(5, uint(1, 0))], + ["wrong struct key wire", bin(5, bin(1, message(uint(1, 0), bin(2, text(3, "x")))))], + ["wrong struct value wire", bin(5, bin(1, message(text(1, "k"), uint(2, 0))))], + ["wrong list item wire", bin(6, uint(1, 0))], + ["nonfinite double", protobufDouble(NaN)], + ["invalid UTF-8", bin(3, Buffer.from([0xff]))], + ["invalid NullValue", uint(1, 1)], + ["excessive nesting", Array.from({ length: 66 }).reduce((v) => bin(6, bin(1, v)), text(3, "nested"))], +] +const REPEATED_MCP_EXEC = Buffer.from("08075a0c2a0a61756469745f6563686f5a030a0561", "hex") +const mcpEntry = (key, value) => bin(2, message(text(1, key), bin(2, value))) +for (const [label, execMessage] of [ + ["truncated second envelope", REPEATED_MCP_EXEC], + ["wrong second wire", message(uint(1, 7), bin(11, text(5, "audit_echo")), uint(11, 0))], + ["recursive second value", message(uint(1, 7), bin(11, text(5, "audit_echo")), bin(11, message(text(5, "audit_echo"), mcpEntry("value", bin(6, bin(1, Buffer.from("1a0561", "hex")))))))], + ["excessive second depth", message(uint(1, 7), bin(11, text(5, "audit_echo")), bin(11, message(text(5, "audit_echo"), mcpEntry("value", MALFORMED_VALUES.find(([label]) => label === "excessive nesting")[1]))))], + ["differing valid arguments", message(uint(1, 7), bin(11, text(5, "audit_echo")), bin(11, message(text(5, "audit_echo"), mcpEntry("value", text(3, "changed")))))], + ["differing valid identity", message(uint(1, 7), bin(11, text(5, "audit_echo")), bin(11, message(text(5, "audit_echo"), text(3, "different-native-call"))))], +]) test(`native loader: repeated MCP ${label} fails before exposing tools or retaining handles`, async () => { + const a = await agent({ execMessage, stateDelay: 10_000 }) + const response = await a.ask(auth(), initial()) + expect(response.status).toBe(502) + expect(response.body.choices).toBeUndefined() + expect(a.results).toEqual([]) + expect(a.closes).toEqual([]) + expect(a.runs).toHaveLength(1) + expect(nativeSessions.entries.size).toBe(0) + expect(nativeSessions.handles.size).toBe(0) + await until(() => a.closedStreams === 1) + expect(a.errors).toEqual([]) +}) + +for (const reordered of [false, true]) test(`native loader: repeated MCP ${reordered ? "canonically equal" : "identical"} envelopes expose one call and submit one result`, async () => { + const entries = [mcpEntry("first", text(3, "one")), mcpEntry("nested", bin(5, bin(1, message(text(1, "__proto__"), bin(2, text(3, "safe"))))))] + const identity = message(text(5, "audit_echo"), text(3, "same-native-call")) + const execMessage = message(uint(1, 7), text(15, "exec-7"), bin(11, message(identity, ...entries)), bin(11, message(identity, ...(reordered ? [...entries].reverse() : entries)))) + const a = await agent({ execMessage, finalAfterFirst: true }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + expect(first.status).toBe(200) + expect(choice(first).message.tool_calls).toHaveLength(1) + expect(JSON.parse(choice(first).message.tool_calls[0].function.arguments)).toEqual({ first: "one", nested: JSON.parse('{"__proto__":"safe"}') }) + const final = await a.ask(account, continueWith(chat, first.body, ["same call once"])) + expect(final.status).toBe(200) + expect(choice(final).message.content).toBe("same call once") + expect(a.results).toHaveLength(1) + expect(a.closes).toEqual([7]) + expect(a.runs).toHaveLength(1) + expect(a.errors).toEqual([]) +}) + +for (const [label, argumentValue] of MALFORMED_VALUES) test(`native loader: native protobuf arguments reject ${label} without publishing calls or submitting results`, async () => { + const a = await agent({ argumentValue }) + const response = await a.ask(auth(), initial()) + expect(response.status).toBe(502) + expect(response.body.choices).toBeUndefined() + expect(a.results).toHaveLength(0) + expect(nativeSessions.entries.size).toBe(0) + expect(nativeSessions.handles.size).toBe(0) + await until(() => a.closedStreams === 1) +}) + +for (const limit of ["argumentBytes", "argumentFields"]) test(`native loader: native protobuf arguments enforce the ${limit} bound`, async () => { + const previous = NATIVE_LIMITS[limit] + NATIVE_LIMITS[limit] = 32 + try { + const argumentValue = limit === "argumentBytes" ? text(3, "x".repeat(64)) : bin(6, message(...Array.from({ length: 40 }, () => bin(1, Buffer.alloc(0))))) + const a = await agent({ argumentValue }) + const response = await a.ask(auth(), initial()) + expect(response.status).toBe(502) + expect(response.body.choices).toBeUndefined() + expect(a.results).toHaveLength(0) + expect(nativeSessions.handles.size).toBe(0) + } finally { + if (previous === undefined) delete NATIVE_LIMITS[limit] + else NATIVE_LIMITS[limit] = previous + } +}) + +for (const [label, argumentValue, expected] of [ + ["unset Value", Buffer.alloc(0), null], + ["explicit null", uint(1, 0), null], + ["empty Struct", bin(5, Buffer.alloc(0)), {}], + ["default map entry", bin(5, bin(1, Buffer.alloc(0))), { "": null }], + ["default list entries", bin(6, message(bin(1, Buffer.alloc(0)), bin(1, uint(4, 0)))), [null, false]], + ["proto key", bin(5, bin(1, message(text(1, "__proto__"), bin(2, text(3, "safe"))))), JSON.parse('{"__proto__":"safe"}')], + ["last oneof value", message(text(3, "old"), uint(4, 1)), true], + ["finite double", protobufDouble(-12.5), -12.5], + ["literal UTF-8 BOM", text(3, "\uFEFFexact"), "\uFEFFexact"], + ["nested Struct/List", bin(5, bin(1, message(text(1, "items"), bin(2, bin(6, message(bin(1, protobufDouble(0)), bin(1, uint(4, 1)), bin(1, text(3, "精确")))))))), { items: [0, true, "精确"] }], +]) test(`native loader: native protobuf arguments preserve protobuf ${label}`, async () => { + const a = await agent({ argumentValue }) + const response = await a.ask(auth(), initial()) + expect(response.status).toBe(200) + expect(JSON.parse(choice(response).message.tool_calls[0].function.arguments)).toEqual({ value: expected }) +}) + +for (const options of [{ name: "unregistered" }, { provider: "foreign" }, { approval: true }]) test("native HTTP/2: unavailable MCP forms are refused without execution and the model continues", async () => { + const a = await agent(options) + const r = await a.ask(auth(), initial()) + expect(r.status).toBe(200) + expect(choice(r).message.content).toBe("continued after unavailable") + expect(a.results).toEqual([]) + expect(a.unavailable).toHaveLength(1) +}) + + +for (const stream of [false, true]) test(`native retention: ${stream ? "streamed" : "JSON"} uncertain result writes are surfaced once; retry rebuilds without native resubmission`, async () => { + const a = await agent({ stateDelay: 10_000 }), account = auth(), chat = initial() + const connect = http2.connect + let req + http2.connect = (...args) => { + const session = connect(...args), request = session.request + session.request = function (...args) { req = request.apply(this, args); return req } + return session + } + try { + const first = await a.ask(account, chat) + const owner = [...nativeSessions.entries][0] + const write = req.write + req.write = function (packet, callback) { + const result = readWire(packet.subarray(5)).some((f) => f.no === 2) + return write.call(this, packet, (e) => { + if (result) setImmediate(() => callback(Object.assign(new Error("synthetic result write failed; outcome uncertain"), { status: 503 }))) + else callback(e) + }) + } + const next = { ...continueWith(chat, first.body, ["provided-once"]), stream } + const failed = await a.ask(account, next) + expect(failed.status).toBe(503) + const body = stream ? await failed.json() : failed.body + expect(body.error.message).toContain("uncertain") + await until(() => a.results.length === 1 && a.closedStreams === 1) + expect(owner.state).toBe("failed") + expect(a.closes).toEqual([]) + // The old hard-error test rejected this retry with 410. Rebuilding imports + // already supplied results; it does not call the external tool or re-send + // a native McpResult whose first write might have reached the server. + rebuilt(await a.ask(account, { ...next, stream: false }), "provided-once") + expect(a.results).toHaveLength(1) + expect(a.runs).toHaveLength(2) + expect(a.errors).toEqual([]) + } finally { http2.connect = connect } +}) + +test("native retention: synchronous result-close overflow does not resubmit its admitted result", async () => { + const a = await agent({ stateDelay: 10_000 }), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const owner = [...nativeSessions.entries][0] + await until(() => owner.transport.outbound.messages === 0) + NATIVE_LIMITS.outboundMessages = 1 + const next = continueWith(chat, first.body, ["admitted-once"]) + const failed = await a.ask(account, next) + expect(failed.status).toBe(503) + expect(failed.body.error.message).toContain("uncertain") + expect(failed.body.error.message).toContain("cannot be replayed") + await until(() => a.closedStreams === 1) + NATIVE_LIMITS.outboundMessages = limits.outboundMessages + rebuilt(await a.ask(account, next), "admitted-once") + expect(a.results.length).toBeLessThanOrEqual(1) + expect(a.closes).toEqual([]) + expect(a.runs).toHaveLength(2) +}) + +test("native retention: concurrent continuation falls back while the original retains its result reservation", async () => { + const a = await agent(), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["concurrent-result"]) + const responses = await Promise.all([a.ask(account, next), a.ask(account, next)]) + expect(responses.map((r) => r.status)).toEqual([200, 200]) + const continued = responses.find((r) => choice(r).finish_reason === "tool_calls") + const fallback = responses.find((r) => choice(r).finish_reason === "stop") + rebuilt(fallback, "concurrent-result") + expect(continued).toBeDefined() + expect(a.results).toHaveLength(1) + expect(a.runs).toHaveLength(2) + const replay = await a.ask(account, next) + expect(choice(replay).message).toEqual(choice(continued).message) + expect(replay.body.usage.total_tokens).toBe(0) + expect(a.results).toHaveLength(1) +}) + +for (const options of [{ noCount: true }, { cleanNoCount: true }]) test(`native retention: missing batch count ${options.noCount ? "deadline" : "clean EOF"} before visible JSON output retries stateless once`, async () => { + NATIVE_LIMITS.batchWait = 45 + const a = await agent(options), account = auth(), chat = initial() + const result = await a.ask(account, chat) + rebuilt(result, "new-input") + expect(result.diagnostic).toContain("reason=missing-batch-count") + expect(choice(result).finish_reason).toBe("stop") + expect(choice(result).message.tool_calls).toBeUndefined() + expect(a.runs).toHaveLength(2) + expect(a.histories[1]).toEqual(a.histories[0]) + expect(a.results).toEqual([]) + expect(a.closes).toEqual([]) +}) + +test("native retention: progressive thinking before missing count is not transparently replayed", async () => { + NATIVE_LIMITS.batchWait = 45 + const a = await agent({ noCount: true }) + const response = await a.ask(auth(), initial({ stream: true })) + const reader = response.body.getReader() + let sse = "" + while (!sse.includes("native planning one")) sse += new TextDecoder().decode((await reader.read()).value) + expect(sse).not.toContain("did not declare") + while (true) { + const part = await reader.read() + if (part.done) break + sse += new TextDecoder().decode(part.value) + } + expect(sse).toContain("did not declare") + expect(sse).not.toContain("rebuilt:") + expect(a.runs).toHaveLength(1) + expect(a.results).toEqual([]) +}) + +test("native retention: prompt_cache_key keeps ownership when the host session changes", async () => { + const a = await agent(), account = auth(), chat = initial({ prompt_cache_key: "synthetic-thread" }) + const first = await a.ask(account, chat, { session: "host-one" }) + const second = await a.ask(account, continueWith(chat, first.body, ["same-cache-key"]), { session: "host-two" }) + expect(second.status).toBe(200) + expect(a.runs).toHaveLength(1) + expect(a.results).toHaveLength(1) +}) + +test("native retention: a missing count before the streaming head can rebuild without duplicate output", async () => { + const a = await agent({ cleanNoCount: true, initialReasoning: "" }) + const response = await a.ask(auth(), initial({ stream: true })) + expect(response.status).toBe(200) + expect(response.headers.get("X-Magpie-Cursor-Continuity")).toContain("reason=missing-batch-count") + const sse = await response.text() + expect(sse).toContain("rebuilt:new-input") + expect(sse).toContain("[DONE]") + expect(sse).not.toContain("native planning one") + expect(a.runs).toHaveLength(2) + expect(a.results).toEqual([]) +}) + +test("native retention: missing count after a native result never transparently reruns that turn", async () => { + NATIVE_LIMITS.batchWait = 45 + const a = await agent({ secondNoCount: true }), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["already submitted"]) + const failed = await a.ask(account, next) + expect(failed.status).toBe(502) + expect(failed.body.error.message).toContain("declared native tool batch") + expect(a.runs).toHaveLength(1) + expect(a.results).toHaveLength(1) + rebuilt(await a.ask(account, next), "already submitted") + expect(a.runs).toHaveLength(2) + expect(a.results).toHaveLength(1) +}) + +test("native retention: exact single-result image suffix preserves images on one Run", async () => { + const a = await agent(), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["synthetic screenshot"]) + next.messages.at(-1).is_error = true + const png = Buffer.from("89504e470d0a1a0a", "hex") + next.messages.push({ role: "user", content: [{ type: "text", text: "Attached image(s) from tool result:" }, + { type: "image_url", image_url: { url: "data:image/png;base64," + png.toString("base64") } }] }) + const before = JSON.stringify(next) + const second = await a.ask(account, next) + expect(second.status).toBe(200) + expect(JSON.stringify(next)).toBe(before) + expect(a.results[0]).toMatchObject({ isError: true, content: [{ type: "text", text: "synthetic screenshot" }, { type: "image", data: png, mimeType: "image/png" }] }) + const final = await a.ask(account, continueWith(next, second.body, ["image checked"])) + expect(final.status).toBe(200) + expect(a.runs).toHaveLength(1) + expect(a.results).toHaveLength(2) +}) + +test("native retention: actual capacity eviction of terminal handles permits later history rebuild", async () => { + NATIVE_LIMITS.perAccount = 1 + const a = await agent({ finalAfterFirst: true }), account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["terminal evicted result"]) + const owner = [...nativeSessions.entries][0] + const final = await a.ask(account, next) + expect(final.status).toBe(200) + expect(owner.state).toBe("complete") + expect(nativeSessions.handles.size).toBe(1) + const fresh = await a.ask(account, initial({ messages: [{ role: "user", content: "replace terminal owner at capacity" }] })) + expect(fresh.status).toBe(200) + expect(nativeSessions.entries.has(owner)).toBe(false) + expect(nativeSessions.handles.size).toBe(0) + rebuilt(await a.ask(account, next), "terminal evicted result") + expect(a.runs).toHaveLength(3) + expect(a.results).toHaveLength(1) +}) + +for (const parallel of [false, true]) test(`native retransmission: sealed ${parallel ? "final parallel" : "single"} exec continues one Run and submits once`, async () => { + const a = await agent({ parallel, duplicate: !parallel, duplicateFinal: parallel, finalAfterFirst: !parallel }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + expect(first.status).toBe(200) + expect(choice(first).message.tool_calls).toHaveLength(parallel ? 2 : 1) + const next = continueWith(chat, first.body, ["sealed-one", "sealed-two"]) + const final = await a.ask(account, next) + expect(final.status).toBe(200) + expect(choice(final).message.content).toBe(parallel ? "sealed-one|sealed-two" : "sealed-one") + const replay = await a.ask(account, next) + expect(replay.body.usage).toMatchObject({ total_tokens: 0, magpie_native: { accounting: "replayed" } }) + expect(a.results.map((r) => r.id).sort()).toEqual(parallel ? [7, 8] : [7]) + expect(a.closes.sort()).toEqual(parallel ? [7, 8] : [7]) + expect(a.runs).toHaveLength(1) + expect(a.errors).toEqual([]) +}) + +for (const changed of [true, false]) test(`native retransmission: sealed ${changed ? "changed duplicate" : "new exec"} remains a protocol failure`, async () => { + const a = await agent({ changedDuplicate: changed, extraExec: !changed, initialReasoning: "" }) + const response = await a.ask(auth(), initial()) + expect(response.status).toBe(502) + expect(response.body.error.message).toContain(changed ? "identity changed" : "batch was sealed") + expect(response.body.choices).toBeUndefined() + expect(nativeSessions.entries.size).toBe(0) + expect(nativeSessions.handles.size).toBe(0) + expect(a.results).toEqual([]) + expect(a.closes).toEqual([]) + expect(a.runs).toHaveLength(1) +}) + +const EARLIER_USAGE = { inputTokens: 11, outputTokens: 3, cacheReadTokens: 100, cacheWriteTokens: 7 } +const LATER_USAGE = { inputTokens: 22, outputTokens: 5, cacheReadTokens: 200, cacheWriteTokens: 9 } +const EARLIER_DEFERRED = { prompt_tokens: 118, completion_tokens: 3, cached_tokens: 100, cache_write_tokens: 7 } +const NATIVE_FINAL_USAGE = message(uint(1, 215), uint(2, 5), uint(3, 200), uint(4, 9)) +const eventFor = (a, run, tokenUsage) => ({ conversationId: string(a.runs[run], 5), timestamp: String(a.started[run] + 2), tokenUsage }) +// The existing dashboard contract identifies Runs by conversation and event +// time. Leave more than its one-second tolerance between distinct Runs here; +// the exact-boundary fixture below separately covers ambiguous timestamps. +const afterEvent = async (event) => { + const ms = Number(event.timestamp) + 1100 - Date.now() + if (ms > 0) await new Promise((r) => setTimeout(r, ms)) +} + +for (const timing of ["ready", "after close"]) test(`native accounting: full capacity stateless E1 then retained E2 collects prior debt ${timing}`, async () => { + NATIVE_LIMITS.perProcess = 1 + const a = await agent({ toolRuns: [1, 2], rebuildUsage: NATIVE_FINAL_USAGE, dashboard: async (fake) => { + if (timing === "after close" && fake.runs.length >= 3) await until(() => fake.closedStreams === 3) + if (fake.runs.length >= 3 && fake.events.length === 1) fake.events.push(eventFor(fake, 2, LATER_USAGE)) + return Response.json({ usageEventsDisplay: fake.events }) + } }) + const account = auth(), chat = initial() + const holderChat = initial({ messages: [{ role: "user", content: "hold the only retained slot" }] }) + expect((await a.ask(account, holderChat, { session: "capacity-holder" })).status).toBe(200) + const holder = [...nativeSessions.entries][0] + const first = await a.ask(account, chat) + expect(first.status).toBe(200) + expect(first.diagnostic).toMatch(/^stateless;/) + expect(first.body.usage.total_tokens).toBe(0) + expect(holder.state).toBe("awaiting-results") + const earlier = eventFor(a, 1, EARLIER_USAGE) + await afterEvent(earlier) + a.events.push(earlier) + await holder.cancel("free the fixture capacity") + const next = continueWith(chat, first.body, ["already-executed-stateless-tool"]) + const final = await a.ask(account, next) + expect(final.status).toBe(200) + expect(final.diagnostic).toMatch(/^same-run;/) + expect(choice(final).message.content).toBe("rebuilt:already-executed-stateless-tool") + expect(final.body.usage).toMatchObject({ prompt_tokens: 215, completion_tokens: 5, total_tokens: 220, + prompt_tokens_details: { cached_tokens: 200, cache_write_tokens: 9 }, magpie_deferred: EARLIER_DEFERRED }) + const owner = [...nativeSessions.entries][0] + expect(owner.state).toBe("complete") + const key = _internal.usageKey(account.access, earlier.conversationId) + expect(_internal.owed.has(key)).toBe(false) + nativeSessions.forget(owner) + await owner.cancel("already completed") + NATIVE_LIMITS.perProcess = 0 + const later = await a.ask(account, next) + expect(later.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.has(key)).toBe(false) + expect(a.runs).toHaveLength(4) + expect(a.results).toEqual([]) + expect(a.closes).toEqual([]) + expect(a.errors).toEqual([]) +}) + +for (const loss of ["expiry", "failure", "cancellation", "forget"]) test(`native accounting: pending handoff ${loss} enrolls E1 once for stateless history E2`, async () => { + if (loss === "expiry") NATIVE_LIMITS.resultWait = 55 + const a = await agent({ rebuildUsage: NATIVE_FINAL_USAGE }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + expect(first.body.usage).toMatchObject({ total_tokens: 0, magpie_native: { accounting: "pending" } }) + const owner = [...nativeSessions.entries][0] + const earlier = eventFor(a, 0, EARLIER_USAGE) + const key = _internal.usageKey(account.access, earlier.conversationId) + expect(_internal.owed.has(key)).toBe(false) + if (loss === "expiry") await until(() => owner.state === "expired") + if (loss === "failure") owner.fail({ status: 502, message: "synthetic abandoned pending Run" }) + if (loss === "cancellation") await owner.cancel("synthetic cancellation after pending handoff") + if (loss === "forget") nativeSessions.forget(owner) + expect(_internal.owed.get(key)?.n).toBe(1) + owner.fail({ status: 502, message: "repeat cleanup" }) + nativeSessions.forget(owner) + await owner.cancel("repeat cancellation") + expect(_internal.owed.get(key)?.n).toBe(1) + await afterEvent(earlier) + a.events.push(earlier) // dashboard delivery occurs after ownership was lost + const next = continueWith(chat, first.body, ["completed-external-tool"]) + const final = await a.ask(account, next) + rebuilt(final, "completed-external-tool") + expect(final.body.usage).toMatchObject({ prompt_tokens: 215, completion_tokens: 5, magpie_deferred: EARLIER_DEFERRED }) + expect(_internal.owed.has(key)).toBe(false) + const retry = await a.ask(account, next) + expect(retry.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.has(key)).toBe(false) + expect(a.runs).toHaveLength(3) + expect(a.results).toEqual([]) + expect(a.closes).toEqual([]) + expect(a.errors).toEqual([]) +}) + +test("native accounting: missing E1 stays bounded past authoritative E2 and a later stateless tool E3", async () => { + NATIVE_LIMITS.perProcess = 0 + const a = await agent({ toolRuns: [1, 3], rebuildUsage: NATIVE_FINAL_USAGE, onRun: (fake) => { + if (fake.runs.length === 2) fake.events.push(eventFor(fake, 1, LATER_USAGE)) + if (fake.runs.length === 3) fake.events.push(eventFor(fake, 2, LATER_USAGE)) + } }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + expect(first.body.usage.total_tokens).toBe(0) + const earlier = eventFor(a, 0, EARLIER_USAGE) + const key = _internal.usageKey(account.access, earlier.conversationId) + await afterEvent(earlier) + NATIVE_LIMITS.perProcess = 1 + const nativeChat = continueWith(chat, first.body, ["E1-result"]) + const nativeFinal = await a.ask(account, nativeChat) + expect(nativeFinal.body.usage).toMatchObject({ prompt_tokens: 215, completion_tokens: 5, total_tokens: 220 }) + expect(nativeFinal.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.get(key)?.n).toBe(1) + await afterEvent(a.events[0]) + NATIVE_LIMITS.perProcess = 0 + const thirdChat = { ...nativeChat, messages: [...nativeChat.messages, choice(nativeFinal).message, { role: "user", content: "E3 request while E1 is still missing" }] } + const third = await a.ask(account, thirdChat) + expect(third.status).toBe(200) + expect(choice(third).finish_reason).toBe("tool_calls") + expect(third.body.usage).toMatchObject({ prompt_tokens: 231, completion_tokens: 5, total_tokens: 236 }) + expect(third.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.get(key)?.n).toBe(1) + a.events.push(earlier) + const fourthChat = continueWith(thirdChat, third.body, ["E3-result"]) + const fourth = await a.ask(account, fourthChat) + expect(fourth.body.usage).toMatchObject({ prompt_tokens: 215, magpie_deferred: EARLIER_DEFERRED }) + expect(_internal.owed.has(key)).toBe(false) + const retry = await a.ask(account, fourthChat) + expect(retry.body.usage.magpie_deferred).toBeUndefined() + expect(a.runs).toHaveLength(5) + expect(a.results).toEqual([]) + expect(a.closes).toEqual([]) + expect(a.errors).toEqual([]) +}) + +test("native accounting: an event exactly at native start remains unknown and bounded debt expires", async () => { + NATIVE_LIMITS.perProcess = 0 + const clock = Date.now + let fixed + const a = await agent({ onRun: (fake) => { if (fake.runs.length === 2) Date.now = clock }, dashboard: (fake) => Response.json({ usageEventsDisplay: fake.events }) }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + const earlier = eventFor(a, 0, EARLIER_USAGE) + const key = _internal.usageKey(account.access, earlier.conversationId) + fixed = clock() + a.events.push({ ...earlier, timestamp: String(fixed) }) + NATIVE_LIMITS.perProcess = 1 + try { + Date.now = () => fixed + const next = continueWith(chat, first.body, ["ambiguous-E1-time"]) + const final = await a.ask(account, next) + expect(final.body.usage.prompt_tokens).toBe(13) + expect(final.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.get(key)?.n).toBe(1) + _internal.STEP_WAIT.owedFor = 1 + await new Promise((r) => setTimeout(r, 5)) + NATIVE_LIMITS.perProcess = 0 + const later = await a.ask(account, next) + expect(later.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.has(key)).toBe(false) + } finally { Date.now = clock } +}) + +test("native accounting: authoritative final zero and cached zero replay never enroll dashboard debt", async () => { + const a = await agent({ finalAfterFirst: true, zeroUsage: true }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + const next = continueWith(chat, first.body, ["zero-accounted-result"]) + const final = await a.ask(account, next) + const owner = [...nativeSessions.entries][0] + const key = _internal.usageKey(account.access, string(a.runs[0], 5)) + expect(final.body.usage).toEqual({ prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, + prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 }, completion_tokens_details: { reasoning_tokens: 0 } }) + const replay = await a.ask(account, next) + expect(replay.body.usage).toMatchObject({ total_tokens: 0, magpie_native: { accounting: "replayed" } }) + nativeSessions.forget(owner) + await owner.cancel("forget an authoritative zero") + expect(_internal.owed.has(key)).toBe(false) + a.events.push(eventFor(a, 0, { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 })) + const rebuiltFinal = await a.ask(account, next) + expect(rebuiltFinal.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.has(key)).toBe(false) + expect(a.dashboardRequests).toEqual([]) + expect(a.runs).toHaveLength(2) + expect(a.results).toHaveLength(1) + expect(a.closes).toEqual([7]) +}) + +test("native accounting: cancellation interrupts final debt collection and preserves E1 for the next request", async () => { + NATIVE_LIMITS.perProcess = 0 + let collecting = false, aborted = false + const a = await agent({ dashboard: async (fake, init) => { + if (fake.events.length && !aborted) { + collecting = true + await new Promise((_, reject) => { + init.signal.addEventListener("abort", () => { aborted = true; reject(init.signal.reason) }, { once: true }) + }) + } + return Response.json({ usageEventsDisplay: fake.events }) + } }) + const account = auth(), chat = initial() + const first = await a.ask(account, chat) + const earlier = eventFor(a, 0, EARLIER_USAGE) + const key = _internal.usageKey(account.access, earlier.conversationId) + await afterEvent(earlier) + a.events.push(earlier) + NATIVE_LIMITS.perProcess = 1 + const next = continueWith(chat, first.body, ["result-before-cancellation"]) + const ac = new AbortController() + const pending = a.ask(account, next, { signal: ac.signal }) + await until(() => collecting && [...nativeSessions.entries][0]?.transportClosed) + const owner = [...nativeSessions.entries][0] + expect(owner.transportClosed).toBe(true) + const at = Date.now() + ac.abort() + expect((await pending).status).toBe(410) + await owner.pumpTask + expect(aborted).toBe(true) + expect(Date.now() - at).toBeLessThan(1000) + expect(_internal.owed.get(key)?.n).toBe(1) + expect(_internal.flights.has(key)).toBe(false) + NATIVE_LIMITS.perProcess = 0 + const later = await a.ask(account, next) + expect(later.body.usage.magpie_deferred).toEqual(EARLIER_DEFERRED) + expect(_internal.owed.has(key)).toBe(false) + expect(a.results).toEqual([]) +}) diff --git a/packages/cursor/native-http1.test.mjs b/packages/cursor/native-http1.test.mjs new file mode 100644 index 0000000..be83192 --- /dev/null +++ b/packages/cursor/native-http1.test.mjs @@ -0,0 +1,260 @@ +import "./nonet.mjs" +import { afterEach, beforeEach, expect, test } from "bun:test" +import http2 from "node:http2" +import { randomUUID } from "node:crypto" +import { CursorAuthPlugin, _internal } from "./index.mjs" +import { NATIVE_LIMITS, nativeSessions } from "./native-session.mjs" +import { readWire, nest, number, string, message, uint, text, update, tool, end, readResult, setBlob, getBlob } from "./native-test-wire.mjs" + +const savedFetch = globalThis.fetch +const servers = [] +const limits = { ...NATIVE_LIMITS } +const usageWait = { ..._internal.STEP_WAIT } +const until = async (predicate) => { + const deadline = Date.now() + 1200 + while (!predicate()) { + if (Date.now() >= deadline) throw new Error("fixture did not reach its expected state") + await new Promise((r) => setTimeout(r, 5)) + } +} +beforeEach(async () => { + await nativeSessions.clear() + _internal.resetH1() + // An abandoned native Run now owes dashboard usage. Scale that empty-event + // wait with this fake rather than outlasting Bun's five-second test budget. + Object.assign(_internal.STEP_WAIT, { first: 0, every: 5, until: 40, ask: 250, owedAt: 1000 }) +}) +afterEach(async () => { + await nativeSessions.clear() + for (const { server, sessions } of servers.splice(0)) { + for (const session of sessions) session.destroy() + await new Promise((r) => server.close(r)) + } + globalThis.fetch = savedFetch + _internal.resetH1() + for (const key of Object.keys(NATIVE_LIMITS)) if (!(key in limits)) delete NATIVE_LIMITS[key] + Object.assign(NATIVE_LIMITS, limits) + Object.assign(_internal.STEP_WAIT, usageWait) + for (const map of [_internal.owed, _internal.flights, _internal.misses, _internal.unreadable]) map.clear() +}) + +// Refusing the local H2 stream exercises the existing RunSSE/BidiAppend path. +// All API calls are synthetic; unknown calls fail instead of leaving localhost. +async function fixture({ failResult = false, stallKv = false } = {}) { + const sessions = new Set() + const server = http2.createServer() + server.on("session", (s) => { sessions.add(s); s.on("error", () => {}); s.on("close", () => sessions.delete(s)) }) + server.on("stream", (s) => { s.on("error", () => {}); s.close(http2.constants.NGHTTP2_REFUSED_STREAM) }) + await new Promise((r) => server.listen(0, "127.0.0.1", r)) + servers.push({ server, sessions }) + const base = `http://127.0.0.1:${server.address().port}` + const seen = { sse: 0, runs: 0, appends: [], results: [], closes: [], kv: [], histories: [], maxInFlight: 0, conversationId: "", dashboardRequests: 0 } + let inFlight = 0 + let controller + let ended = false + let requestID + let bootstrap = new Map(), imported = [] + const push = (b) => { if (!ended) controller.enqueue(b) } + const finish = () => { + if (ended) return + push(end()) + ended = true + controller.close() + } + globalThis.fetch = async (url, init = {}) => { + const u = String(url) + if (u.endsWith("/aiserver.v1.ServerConfigService/GetServerConfig")) return Response.json({ agentUrlConfig: { agentUrl: base } }) + if (u.endsWith("/agent.v1.AgentService/GetUsableModels")) return Response.json({ models: [{ modelId: "synthetic-h1-model", displayName: "Synthetic H1" }] }) + if (u.endsWith("/aiserver.v1.DashboardService/GetFilteredUsageEvents")) { + seen.dashboardRequests++ + return Response.json({ usageEventsDisplay: [] }) + } + if (u.endsWith("/agent.v1.AgentService/RunSSE")) { + seen.sse++ + ended = false + requestID = string(Buffer.from(init.body).subarray(5), 1) + return new Response(new ReadableStream({ + start(c) { + controller = c + init.signal.addEventListener("abort", () => { + if (ended) return + ended = true + c.close() + }, { once: true }) + }, + })) + } + if (!u.endsWith("/aiserver.v1.BidiService/BidiAppend")) throw new Error("unexpected synthetic API call: " + u) + const body = Buffer.from(init.body) + expect(string(nest(body, 2), 1)).toBe(requestID) + const seqno = number(body, 3) + const wire = Buffer.from(string(body, 1), "hex") + inFlight++ + seen.maxInFlight = Math.max(seen.maxInFlight, inFlight) + seen.appends.push(seqno) + try { + const fs = readWire(wire) + if (fs.some((f) => f.no === 1)) { + seen.runs++ + seen.conversationId = string(nest(wire, 1), 5) + if (seen.runs > 1) { + imported = [] + seen.histories.push(imported) + const refs = readWire(nest(nest(wire, 1), 1)).filter((f) => f.no === 1) + bootstrap = new Map(refs.map((f, i) => [1000 + i, i])) + for (const [i, ref] of refs.entries()) push(getBlob(1000 + i, ref.data)) + return new Response(new Uint8Array(0)) + } + push(update(4, text(1, "synthetic native thinking one"))) + push(update(27, uint(1, 1))) + push(tool(7, "h1-native-call-one")) + } else if (fs.some((f) => f.no === 2)) { + const result = readResult(wire) + expect(result.execID).toBe("exec-" + result.id) + expect(seen.results.some((r) => r.id === result.id)).toBe(false) + seen.results.push(result) + // Hold the result append so a premature/concurrent close is observable. + await new Promise((r) => setTimeout(r, 25)) + if (failResult) return new Response('{"code":"unavailable","message":"synthetic append failed after receiving result"}', { status: 503 }) + } else if (fs.some((f) => f.no === 5)) { + const control = nest(wire, 5) + const close = readWire(control).find((f) => f.no === 1) + if (close) { + const id = number(close.data, 1) + const result = seen.results.find((r) => r.id === id) + expect(result).toBeDefined() + expect(seen.closes).not.toContain(id) + seen.closes.push(id) + if (id === 7) { + push(update(4, text(1, "synthetic native thinking two"))) + push(tool(8, "h1-native-call-two", result.content[0].text)) + push(update(27, uint(1, 1))) + } else { + push(update(1, text(1, result.content[0].text))) + push(update(14, message(uint(1, 17), uint(2, 5), uint(3, 11)))) + finish() + } + } + } else if (fs.some((f) => f.no === 3)) { + const kv = nest(wire, 3) + const id = number(kv, 1) + seen.kv.push(id) + if (bootstrap.has(id)) { + imported[bootstrap.get(id)] = JSON.parse(nest(nest(kv, 2), 1).toString()) + bootstrap.delete(id) + if (!bootstrap.size) { + const marker = imported.filter((m) => m.role === "tool").flatMap((m) => m.content).flatMap((r) => r.experimental_content ?? []).map((r) => r.text).join("|") + push(update(1, text(1, "rebuilt:" + marker))) + push(update(14, message(uint(1, 13), uint(2, 4)))) + finish() + } + } + if (stallKv && readWire(kv).some((f) => f.no === 2)) await new Promise((_, reject) => { + if (init.signal.aborted) reject(init.signal.reason) + else init.signal.addEventListener("abort", () => reject(init.signal.reason), { once: true }) + }) + } + return new Response(new Uint8Array(0)) + } finally { + inFlight-- + } + } + const account = { + type: "oauth", + access: `e30.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 7200, sub: "synthetic-h1-" + randomUUID() })).toString("base64url")}.fixture`, + refresh: "", accountId: "fixture@example.invalid", + } + const plugin = await CursorAuthPlugin() + const loader = await plugin.auth.loader(async () => account) + const ask = async (chat) => { + const response = await loader.fetch(base + "/v1/chat/completions", { + method: "POST", headers: { "x-magpie-cursor-session": "synthetic-h1-session" }, body: JSON.stringify(chat), + }) + if (chat.stream) return response + return { status: response.status, body: await response.json() } + } + return { seen, ask, account, push, ended: () => ended, inFlight: () => inFlight } +} +const initial = () => ({ model: "synthetic-h1-model", messages: [{ role: "user", content: "two synthetic calls" }], + tools: [{ type: "function", function: { name: "audit_echo", parameters: { type: "object" } } }] }) +const continuation = (chat, response, value) => ({ ...chat, messages: [...chat.messages, response.body.choices[0].message, + { role: "tool", tool_call_id: response.body.choices[0].message.tool_calls[0].id, content: value }] }) + +test("native HTTP/1: two external roundtrips keep one RunSSE and serialize result-before-close BidiAppends", async () => { + const { seen, ask } = await fixture() + const chat = initial() + const first = await ask(chat) + expect(first.status).toBe(200) + const marker = "synthetic-h1-result-" + randomUUID() + const secondChat = continuation(chat, first, marker) + const second = await ask(secondChat) + expect(second.status).toBe(200) + expect(JSON.parse(second.body.choices[0].message.tool_calls[0].function.arguments)).toEqual({ value: marker }) + const final = await ask(continuation(secondChat, second, marker)) + expect(final.status).toBe(200) + expect(final.body.choices[0].message.content).toBe(marker) + expect(final.body.choices[0].finish_reason).toBe("stop") + expect(final.body.usage.prompt_tokens).toBe(17) + expect(final.body.usage.completion_tokens).toBe(5) + expect(seen).toMatchObject({ sse: 1, runs: 1, appends: [0, 1, 2, 3, 4], closes: [7, 8], maxInFlight: 1 }) + expect(seen.results.map((r) => r.id)).toEqual([7, 8]) +}) + +for (const bound of ["bytes", "messages"]) test(`native loader HTTP/1: stalled parked KV replies hit the outbound ${bound} bound and abort all transport work`, async () => { + NATIVE_LIMITS.outboundBytes = 4 << 20 + NATIVE_LIMITS.outboundMessages = bound === "messages" ? 4 : 256 + const a = await fixture({ stallKv: true }) + const chat = initial() + const first = await a.ask(chat) + expect(first.status).toBe(200) + const owner = [...nativeSessions.entries][0] + const blobID = Buffer.from("synthetic-queued-blob") + a.push(setBlob(90, blobID, Buffer.alloc(bound === "bytes" ? 1 << 20 : 1))) + await until(() => a.seen.kv.includes(90) && a.inFlight() === 0) + a.push(getBlob(91, blobID)) + await until(() => a.seen.kv.includes(91)) + for (let i = 0; i < 8; i++) a.push(getBlob(92 + i, blobID)) + await until(() => !!owner.error) + expect(owner.error).toMatchObject({ status: 503 }) + expect(owner.error.message).toContain("outbound") + expect(owner.error.message).toContain(bound) + await until(() => a.inFlight() === 0 && a.ended()) + expect(owner.transport.outbound).toEqual({ bytes: 0, messages: 0 }) + expect(owner.ac.signal.aborted).toBe(true) + expect(a.seen.kv).toEqual([90, 91]) + expect(a.seen.maxInFlight).toBe(1) + expect(a.seen.results).toEqual([]) + expect(a.seen.closes).toEqual([]) + // Retention overflow ends this owner. A later request is history input to + // the stateless path, covered with a rebuilding server in native-e2e. + expect(nativeSessions.prepare("unrelated-account", continuation(chat, first, "late after overflow"), "synthetic-selector", []).fallback).toBeTruthy() +}) + +for (const stream of [false, true]) test(`native HTTP/1: ${stream ? "streamed" : "JSON"} uncertain append is reported once; supplied history can rebuild`, async () => { + const { seen, ask, account } = await fixture({ failResult: true }) + const chat = initial(), first = await ask(chat) + const owner = [...nativeSessions.entries][0] + const next = { ...continuation(chat, first, "synthetic uncertain result"), stream } + const failed = await ask(next) + expect(failed.status).toBe(503) + const body = stream ? await failed.json() : failed.body + expect(body.error.message).toContain("append failed") + expect(seen.results).toHaveLength(1) + expect(seen.closes).toEqual([]) + expect(owner.state).toBe("failed") + const key = _internal.usageKey(account.access, seen.conversationId) + expect(_internal.owed.get(key)?.n).toBe(1) + // A missing owner is optional retention, including an uncertain prior append. + // Reuse the provided result in imported history; never resubmit its native exec. + const rebuilt = await ask({ ...next, stream: false }) + expect(rebuilt.status).toBe(200) + expect(rebuilt.body.choices[0].message.content).toBe("rebuilt:synthetic uncertain result") + expect(rebuilt.body.usage.magpie_deferred).toBeUndefined() + expect(_internal.owed.get(key)?.n).toBe(1) // absent dashboard count stays unknown + expect(seen.dashboardRequests).toBeGreaterThan(0) + expect(seen.runs).toBe(2) + expect(seen.sse).toBe(2) + expect(seen.results).toHaveLength(1) + expect(seen.closes).toEqual([]) + expect(seen.maxInFlight).toBe(1) +}) diff --git a/packages/cursor/native-session.mjs b/packages/cursor/native-session.mjs new file mode 100644 index 0000000..3317ec4 --- /dev/null +++ b/packages/cursor/native-session.mjs @@ -0,0 +1,845 @@ +import { createHash, randomBytes } from "node:crypto" + +// Retention is process-local and optional. A lost owner rebuilds Chat history +// on a fresh Run; it never resubmits a result to an uncertain native exec. +// Checkpoints are retained evidence, not restart handles. +export const NATIVE_LIMITS = { + resultWait: 120_000, + lifetime: 15 * 60_000, + batchWait: 30_000, + drain: 6000, + replayWait: 120_000, + blobBytes: 64 << 20, + outputBytes: 16 << 20, + argumentBytes: 1 << 20, + argumentFields: 100_000, + argumentDepth: 64, + outboundBytes: 16 << 20, + outboundMessages: 256, + perAccount: 8, + perProcess: 32, +} + +const HANDLE = /^call_cursor_[a-f0-9]+_\d+_\d+$/ +const hash = (s) => createHash("sha256").update(s).digest("hex") +const canonical = (v) => JSON.stringify(v, (_k, x) => x && typeof x === "object" && !Array.isArray(x) + ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x) +const bytes = (v) => Buffer.byteLength(canonical(v)) +const later = (fn, ms) => { + const timer = setTimeout(fn, ms) + timer.unref?.() + return timer +} + +export class NativeSessionError extends Error { + constructor(status, message) { + super(message) + this.status = status + } +} +const invalid = (message, status = 409) => { throw new NativeSessionError(status, message) } +const failureOf = (e) => ({ status: e?.status ?? 502, message: e?.message ?? String(e) }) + +// Unlike the compatibility codec, malformed protobuf tails must fail a live +// continuation. Dropping one could turn a truncated batch into a valid handoff. +export function nativeFields(input, maxFields = Infinity) { + const b = Buffer.from(input) + const out = [] + let at = 0 + const uv = () => { + let n = 0 + let scale = 1 + for (let i = 0; i < 10 && at < b.length; i++) { + const c = b[at++] + n += (c & 127) * scale + if (c < 128 && Number.isSafeInteger(n)) return n + scale *= 128 + } + invalid("malformed native protobuf", 502) + } + while (at < b.length) { + const key = uv() + const num = Math.floor(key / 8) + const wire = key % 8 + if (!num || num > 0x1fffffff) invalid("malformed native protobuf field", 502) + let n = 0 + let data = Buffer.alloc(0) + if (wire === 0) n = uv() + else if (wire === 2 || wire === 1 || wire === 5) { + const size = wire === 2 ? uv() : wire === 1 ? 8 : 4 + if (at + size > b.length) invalid("truncated native protobuf", 502) + data = b.subarray(at, at + size) + at += size + } else invalid("unsupported native protobuf wire type", 502) + if (out.length >= maxFields) invalid("native protobuf field limit reached", 502) + out.push({ num, wire, n, data }) + } + return out +} +// Decode every known Value kind, including overwritten oneof/map fields, so +// corrupt bytes cannot become different, valid JSON through prefix decoding. +// Missing scalar/map values keep protobuf defaults; unknown fields are skipped +// only after their complete wire envelope has passed validation. +export function nativeMcpArgs(input, limits = NATIVE_LIMITS) { + if (input.length > limits.argumentBytes) invalid("native MCP argument byte limit reached", 502) + let remaining = limits.argumentFields + const read = (b) => { + const fs = nativeFields(b, remaining) + remaining -= fs.length + return fs + } + const typed = (f, wire) => { + if (f.wire !== wire) invalid("invalid native MCP argument field type", 502) + } + const utf8 = (b) => { + try { return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(b) } + catch { invalid("invalid UTF-8 in native MCP arguments", 502) } + } + function mapEntry(b, depth) { + let key = "", value = null + for (const f of read(b)) { + if (f.num === 1) { typed(f, 2); key = utf8(f.data) } + else if (f.num === 2) { typed(f, 2); value = decodeValue(f.data, depth) } + } + return [key, value] + } + function decodeStruct(b, depth) { + const entries = [] + for (const f of read(b)) if (f.num === 1) { + typed(f, 2) + entries.push(mapEntry(f.data, depth)) + } + return Object.fromEntries(entries) + } + function decodeValue(b, depth = 0) { + if (depth > limits.argumentDepth) invalid("native MCP argument nesting limit reached", 502) + let value = null + for (const f of read(b)) { + if (f.num < 1 || f.num > 6) continue + typed(f, [0, 1, 2, 0, 2, 2][f.num - 1]) + switch (f.num) { + case 1: + if (f.n !== 0) invalid("invalid native protobuf NullValue", 502) + value = null + break + case 2: + value = f.data.readDoubleLE(0) + if (!Number.isFinite(value)) invalid("nonfinite native MCP argument number", 502) + break + case 3: value = utf8(f.data); break + case 4: value = f.n !== 0; break + case 5: value = decodeStruct(f.data, depth + 1); break + case 6: + value = [] + for (const item of read(f.data)) if (item.num === 1) { + typed(item, 2) + value.push(decodeValue(item.data, depth + 1)) + } + break + } + } + return value + } + const fs = read(input), entries = [] + for (const f of fs) { + if ([1, 3, 4, 5, 9].includes(f.num)) { typed(f, 2); utf8(f.data) } + else if (f.num === 2) { typed(f, 2); entries.push(mapEntry(f.data, 0)) } + else if (f.num === 6) typed(f, 2) + else if (f.num === 7) typed(f, 0) + } + return { fields: fs, args: Object.fromEntries(entries) } +} + +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 + +function argsOf(s) { + try { + const v = typeof s === "string" ? JSON.parse(s) : s + if (v && typeof v === "object" && !Array.isArray(v)) return v + } catch {} + invalid("invalid tool arguments in native continuation", 400) +} +// These conversions only decide whether a retained exec can be continued. +// Unsupported parts make that request use the legacy history builder instead +// of imposing a new Chat request contract on all callers. +function assistantDisplay(message) { + const parts = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content ?? [] + if (!Array.isArray(parts) || parts.some((p) => !["text", "reasoning"].includes(p?.type) || typeof p.text !== "string")) invalid("unsupported native assistant display") + const reasoning = [message.reasoning_content, message.reasoning, message.reasoning_text].find((v) => typeof v === "string" && v.trim()) ?? "" + return { + text: parts.filter((p) => p.type === "text").map((p) => p.text).join(""), + reasoning: reasoning + parts.filter((p) => p.type === "reasoning").map((p) => p.text).join(""), + } +} +function resultParts(message, limits) { + const parts = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content + if (!Array.isArray(parts)) invalid("unsupported native tool result") + let retained = 0 + return parts.map((part) => { + if (part?.type === "text" && typeof part.text === "string") { + retained += Buffer.byteLength(part.text) + if (retained > limits.outputBytes) invalid("native tool result limit reached") + return { text: part.text } + } + const url = part?.type === "image_url" ? (typeof part.image_url === "string" ? part.image_url : part.image_url?.url) + : part?.type === "image" && part.source?.type === "base64" ? `data:${part.source.media_type};base64,${part.source.data}` : "" + const image = /^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]*={0,2})$/.exec(url ?? "") + if (!image) invalid("unsupported native tool result content") + const data = Buffer.from(image[2], "base64") + retained += data.length + if (retained > limits.outputBytes) invalid("native tool result limit reached") + if (!data.length || data.toString("base64").replace(/=+$/, "") !== image[2].replace(/=+$/, "")) invalid("invalid native result image") + return { data, mimeType: image[1] } + }) +} +function normalizeMessage(m) { + if (m?.role !== "assistant") return m + const { text, reasoning } = assistantDisplay(m) + const out = { ...m, content: text } + delete out.reasoning + delete out.reasoning_content + delete out.reasoning_text + if (reasoning) out.reasoning_content = reasoning + if (m.tool_calls) out.tool_calls = m.tool_calls.map((c) => ({ + ...c, type: c.type ?? "function", function: { ...c.function, arguments: argsOf(c.function?.arguments ?? "{}") }, + })) + return out +} +const historyDigest = (messages) => hash(canonical(messages.map(normalizeMessage))) +function controlsOf(chat, selector, tools) { + const controls = { ...chat } + for (const k of ["messages", "stream", "stream_options"]) delete controls[k] + return hash(canonical({ selector, controls, tools })) +} +const toolAttachment = (m) => m?.role === "user" && Array.isArray(m.content) && m.content.length > 1 + && m.content[0]?.type === "text" && m.content[0].text === "Attached image(s) from tool result:" + && m.content.slice(1).every((p) => p?.type === "image_url") +// A complete result batch is validated before reserving or writing any exec. +// Only the current exported assistant may omit display reasoning. All earlier +// accepted history must match, including instruction order and attachments. +function matchResults(batch, messages) { + if (historyDigest(messages.slice(0, batch.prefixLength)) !== batch.prefixDigest) invalid("native continuation history diverged") + const suffix = messages.slice(batch.prefixLength) + const assistants = [] + while (suffix[assistants.length]?.role === "assistant") assistants.push(suffix[assistants.length]) + if (!assistants.length) invalid("native continuation is missing its assistant tool calls", 400) + let content = "" + let reasoning = "" + const calls = [] + for (const m of assistants) { + const unknown = Object.keys(m).filter((k) => !["role", "content", "tool_calls", "reasoning", "reasoning_content", "reasoning_text"].includes(k)) + if (unknown.length) invalid("unsupported assistant fields in native continuation", 400) + const display = assistantDisplay(m) + content += display.text + reasoning += display.reasoning + for (const c of m.tool_calls ?? []) { + if (c.type && c.type !== "function") invalid("unsupported native continuation tool call", 400) + calls.push({ id: c.id, name: c.function?.name, args: argsOf(c.function?.arguments ?? "{}") }) + } + } + if (content !== batch.content || reasoning && reasoning !== batch.reasoning) invalid("native continuation assistant output changed") + const expected = batch.calls.map((c) => ({ id: c.id, name: c.name, args: argsOf(c.args) })) + const sorted = (v) => [...v].sort((a, b) => String(a.id).localeCompare(String(b.id))) + if (canonical(sorted(calls)) !== canonical(sorted(expected))) invalid("native continuation tool calls changed") + let results = suffix.slice(assistants.length) + // Pi's exact image suffix has no call IDs. Only a single complete result + // gives it unambiguous ownership; all other shapes rebuild legacy history. + if (batch.calls.length === 1 && results.length === 2 && results[0]?.role === "tool" && toolAttachment(results[1])) { + const [result, attachment] = results + const content = typeof result.content === "string" ? [{ type: "text", text: result.content }] : result.content + if (!Array.isArray(content)) invalid("unsupported native tool result") + results = [{ ...result, content: [...content, ...attachment.content.slice(1)] }] + } + if (results.some((m) => m?.role !== "tool")) invalid("new input cannot be interleaved with pending native results") + const ids = new Set() + for (const m of results) { + if (ids.has(m.tool_call_id)) invalid("duplicate native tool result", 400) + ids.add(m.tool_call_id) + if (!expected.some((c) => c.id === m.tool_call_id)) invalid("unknown native tool result", 400) + } + if (ids.size !== expected.length) invalid("all parallel native tool results must be submitted together", 400) + return [...results].sort((a, b) => a.tool_call_id.localeCompare(b.tool_call_id)) +} + +class Segment { + constructor(owner, chat) { + this.owner = owner + this.prefixLength = chat.messages.length + this.prefixDigest = historyDigest(chat.messages) + this.events = [] + this.calls = [] + this.content = "" + this.reasoning = "" + this.expected = null + this.closed = false + this.clean = false + this.waiters = new Set() + } + wake() { + for (const wake of this.waiters) wake() + this.waiters.clear() + } + emit(e) { + this.owner.retain(bytes(e)) + if (e.text) this.content += e.text + if (e.reasoning) this.reasoning += e.reasoning + this.events.push(e) + this.wake() + } + finish(stop) { + for (const [index, c] of this.calls.entries()) { + const e = { tool: { index, id: c.id, name: c.name, args: c.args } } + this.owner.retain(bytes(e)) + this.events.push(e) + } + this.owner.retain(bytes(stop)) + this.events.push(stop) + this.closed = true + this.wake() + } + fail(error) { + // Errors also override a sealed, as yet undelivered handoff. + this.events = [{ error }] + this.closed = true + this.wake() + } + iterator({ replay = false } = {}) { + const segment = this + let at = 0 + let errorSent = false + return { + async next() { + while (!segment.closed && at >= segment.events.length) await new Promise((r) => segment.waiters.add(r)) + if (!replay && segment.owner.error) { + if (errorSent) return { done: true } + errorSent = true + return { value: { error: segment.owner.error }, done: false } + } + if (at < segment.events.length) { + const event = segment.events[at++] + if (replay && event.stop) return { value: { ...event, usage: { + prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, + prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 }, + magpie_native: { accounting: "replayed" }, + } }, done: false } + return { value: event, done: false } + } + return { done: true } + }, + async return() { + if (!replay) await segment.owner.cancel("the Chat response was cancelled") + return { done: true } + }, + [Symbol.asyncIterator]() { return this }, + } + } +} + +export class NativeSessionPool { + constructor(limits = NATIVE_LIMITS) { + this.limits = limits + this.entries = new Set() + this.handles = new Map() + this.selectors = new Map() + } + // selector is conversationID(chat, session): session/cache key AND first + // user identity. Task subagents sharing a session must not own its parent. + prepare(tok, chat, selector, tools) { + const fallback = (reason) => ({ fallback: reason }) + if (!Array.isArray(chat.messages) || bytes(chat) > this.limits.outputBytes) return fallback("history retention limit") + const account = hash(tok) + const controls = controlsOf(chat, selector, tools) + const trailing = [] + const end = chat.messages.length - (toolAttachment(chat.messages.at(-1)) ? 2 : 1) + for (let i = end; i >= 0 && chat.messages[i]?.role === "tool"; i--) trailing.push(chat.messages[i].tool_call_id) + const handles = trailing.filter((id) => typeof id === "string" && HANDLE.test(id)) + if (handles.length) { + // Look up ownership before inspecting native history. Restarted callers + // only need the same permissive history shape the stateless path accepts. + const found = handles.map((id) => this.handles.get(id)) + if (found.some((v) => !v)) return fallback("owner unavailable") + const { owner, batch } = found[0] + if (found.some((v) => v.owner !== owner || v.batch !== batch)) return fallback("different native batches") + if (owner.account !== account || owner.controls !== controls || owner.error) return fallback("owner incompatible or expired") + try { + const results = matchResults(batch, chat.messages) + // Encoding is pure for the entire batch before any reservation or write. + const encoded = results.map((m) => owner.encodeResult(m)) + const digest = hash(canonical(results)) + if (batch.resultDigest) { + // An uncertain or concurrent write is never submitted twice to this + // exec. History reconstruction uses provided results as imported data. + if (batch.resultDigest !== digest || !batch.next?.clean) return fallback("result already submitted or busy") + return { owner, batch, replay: true, segment: batch.next } + } + if (owner.state !== "awaiting-results" || owner.segment !== batch || !batch.clean) return fallback("owner busy") + return { owner, batch, results, encoded, digest, chat } + } catch (e) { + if (!(e instanceof NativeSessionError)) throw e + return fallback("history incompatible with retained owner") + } + } + // Pending ancestors, new input, and terminal old handles are ordinary + // imported history, even while a parent Run is still awaiting its results. + if (chat.messages.some((m) => m?.tool_calls?.some((c) => HANDLE.test(c?.id ?? "")))) return fallback("historical native calls") + if (selector && this.selectors.has(account + ":" + selector)) return fallback("owner busy") + return { account, selector, controls, selected: !!selector, chat } + } + create(prepared, resolution, wire) { + if (prepared.fallback || prepared.selected && this.selectors.has(prepared.account + ":" + prepared.selector)) return null + const crowded = () => this.entries.size >= this.limits.perProcess || [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount + while (crowded()) { + const accountFull = [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount + const finished = [...this.entries].find((e) => ["complete", "failed", "cancelled", "expired"].includes(e.state) && (!accountFull || e.account === prepared.account)) + if (!finished) return null + this.forget(finished) + } + let owner + try { owner = new NativeSession(this, prepared, resolution, wire) } + catch (e) { + if (!(e instanceof NativeSessionError)) throw e + return null + } + this.entries.add(owner) + if (prepared.selected) this.selectors.set(owner.account + ":" + owner.selector, owner) + return owner + } + release(owner) { + const key = owner.account + ":" + owner.selector + if (this.selectors.get(key) === owner) this.selectors.delete(key) + } + forget(owner) { + owner.accounting?.abandon() + clearTimeout(owner.replayTimer) + this.release(owner) + this.entries.delete(owner) + for (const [id, h] of this.handles) if (h.owner === owner) this.handles.delete(id) + owner.blobs.clear() + owner.checkpoint = null + owner.execs.clear() + owner.nativeCalls.clear() + } + async clear() { + await Promise.all([...this.entries].map((e) => e.cancel("native owner removed"))) + for (const e of this.entries) { + clearTimeout(e.replayTimer) + this.forget(e) + } + } +} + +class NativeSession { + constructor(pool, prepared, resolution, wire) { + Object.assign(this, prepared) + this.pool = pool + this.limits = pool.limits + this.resolution = resolution + this.wire = wire + this.identity = randomBytes(12).toString("hex") + this.state = "opening" + this.ac = new AbortController() + this.execs = new Map() + this.nativeCalls = new Map() + this.blobs = new Map() + this.knownHashes = new Set() + this.blobSize = 0 + this.retainedBytes = 0 + this.sequence = 0 + this.segments = 0 + this.said = 0 + this.wrote = 0 + this.terminal = false + this.segment = new Segment(this, prepared.chat) + this.retain(bytes(prepared.chat)) + this.lifetimeTimer = later(() => this.fail({ status: 410, message: "native Run lifetime expired" }, "expired"), this.limits.lifetime) + } + retain(n) { + if (this.retainedBytes + n > this.limits.outputBytes) invalid("native output/history retention limit reached", 503) + this.retainedBytes += n + } + attach(signal, segment = this.segment) { + if (signal?.aborted) { + this.fail({ status: 410, message: "the Chat request was already cancelled" }, "cancelled") + return + } + const abort = () => this.fail({ status: 410, message: "the Chat request was cancelled" }, "cancelled") + signal?.addEventListener("abort", abort, { once: true }) + segment.detach = () => signal?.removeEventListener("abort", abort) + } + delivered(segment = this.segment) { + if (this.error) return + segment.clean = true + segment.detach?.() + if (this.state === "complete" && segment === this.segment) this.accounting?.delivered() + } + closeTransport() { + if (this.transportClosed) return + this.transportClosed = true + clearInterval(this.runHeartbeat) + clearInterval(this.execHeartbeat) + clearTimeout(this.batchTimer) + clearTimeout(this.resultTimer) + clearTimeout(this.drainTimer) + clearTimeout(this.lifetimeTimer) + this.ac.abort() + this.transport?.close() + } + fail(error, state = "failed") { + if (this.error || this.state === "complete") return + this.error = error + this.state = state + this.segment.fail(error) + for (const segment of this.batches ?? []) segment.detach?.() + this.segment.detach?.() + this.closeTransport() + // A failed transport has no reusable execs. Forget its handles immediately; + // subsequent caller-supplied history takes the stateless path. + this.pool.forget(this) + } + async cancel(message) { + this.fail({ status: 410, message }, "cancelled") + await this.pumpTask + } + bind(transport, blobs, estimate) { + if (this.transportClosed || this.error) { + transport.close() + return + } + this.transport = transport + this.estimate = estimate + this.blobs = blobs + this.knownHashes = new Set(blobs.keys()) + this.blobSize = [...blobs.values()].reduce((n, b) => n + b.length, 0) + if (this.blobSize > this.limits.blobBytes) invalid("native bootstrap blob limit reached", 503) + if (this.error) return this.closeTransport() + this.state = "running" + const { pb } = this.wire + const heartbeat = (message) => { + try { this.send(message) } catch (e) { this.fail(failureOf(e)) } + } + this.runHeartbeat = setInterval(() => heartbeat(pb().bytes(7, Buffer.alloc(0)).done()), 5000) + this.execHeartbeat = setInterval(() => { + for (const c of this.execs.values()) if (!c.submitted) heartbeat(pb().bytes(5, pb().bytes(3, pb().varint(1, c.requestID))).done()) + }, 3000) + this.runHeartbeat.unref?.() + this.execHeartbeat.unref?.() + } + send(message) { + if (this.error || this.transportClosed) invalid("native transport is no longer writable", 410) + this.transport.send(message) + } + execClose(id) { + this.send(this.wire.pb().bytes(5, this.wire.pb().bytes(1, this.wire.pb().varint(1, id))).done()) + } + encodeResult(message) { + const { pb } = this.wire + const success = pb() + for (const item of resultParts(message, this.limits)) { + if (item.text !== undefined) success.bytes(1, pb().bytes(1, pb().str(1, item.text))) + else success.bytes(1, pb().bytes(2, pb().bytes(1, item.data).str(2, item.mimeType))) + } + if (message.is_error === true || message.isError === true) success.varint(2, 1) + return pb().bytes(1, success).done() // McpResult.success, not stored McpToolResult + } + resume(prepared, signal) { + if (prepared.replay) return this.response(prepared.segment, true) + const batch = prepared.batch + if (this.error || this.state !== "awaiting-results" || this.segment !== batch || batch.resultDigest) invalid("native continuation is already reserved") + const next = new Segment(this, prepared.chat) + this.attach(signal, next) + if (this.error) invalid(this.error.message, this.error.status) + // Reserve synchronously. Competing continuations cannot interleave writes. + batch.resultDigest = prepared.digest + batch.next = next + this.segment = next + this.state = "submitting" + clearTimeout(this.resultTimer) + clearTimeout(this.batchTimer) + try { + for (let i = 0; i < prepared.results.length; i++) { + const call = batch.calls.find((c) => c.id === prepared.results[i].tool_call_id) + const msg = this.wire.pb().varint(1, call.requestID) + if (call.execID) msg.str(15, call.execID) + msg.bytes(11, prepared.encoded[i]) + this.resultSubmitted = true + this.send(this.wire.pb().bytes(2, msg).done()) + call.submitted = true + this.execClose(call.requestID) + } + this.state = "running" + } catch (e) { + const error = failureOf(e) + this.fail({ status: error.status, message: `${error.message}; native result submission failed; its outcome is uncertain and cannot be replayed` }) + } + return this.response(next) + } + response(segment = this.segment, replay = false) { + return { + events: segment.iterator({ replay }), + cancel: () => replay ? Promise.resolve() : this.cancel("the Chat response was cancelled"), + resolution: this.resolution, + delivered: () => replay || this.delivered(segment), + diagnostic: `same-run; bootstrap=imported-history; new-turn=stateless; missing-owner=stateless${replay ? "; replay=true" : ""}`, + } + } + acceptCall(call) { + if (!Number.isInteger(call.requestID)) invalid("native tool call is missing its exec request ID", 502) + const prior = this.execs.get(call.requestID) + const digest = hash(canonical({ requestID: call.requestID, execID: call.execID, nativeID: call.nativeID, name: call.name, args: argsOf(call.args) })) + if (prior) { + if (prior.digest !== digest) invalid("native exec identity changed during retransmission", 502) + return + } + // A retransmission of the final exec can arrive after it sealed its batch. + // Validate that identity first; only a new exec violates the sealed phase. + if (this.terminal || this.state === "awaiting-results") invalid("native call arrived after its batch was sealed", 502) + if (call.nativeID && this.nativeCalls.has(call.nativeID)) invalid("native tool-call ID was reused for another exec", 502) + call.id = `call_cursor_${this.identity}_${this.segments}_${this.segment.calls.length}` + call.digest = digest + this.execs.set(call.requestID, call) + if (call.nativeID) this.nativeCalls.set(call.nativeID, call) + this.segment.calls.push(call) + this.retain(bytes(call)) + this.said += call.args.length + this.waitForBatch() + this.sealBatch() + } + waitForBatch() { + this.batchTimer ??= later(() => { + if (this.segment.expected == null && this.segment.calls.length && !this.resultSubmitted) this.missingCount() + else this.fail({ status: 502, message: "Cursor did not complete its declared native tool batch" }) + }, this.limits.batchWait) + } + missingCount() { + this.fail({ status: 502, message: "Cursor did not declare its native tool batch", retentionIneligible: !this.resultSubmitted }) + } + listed(count) { + if (!Number.isSafeInteger(count) || count < 1) invalid("invalid native tool count", 502) + if (this.segment.expected != null && this.segment.expected !== count) invalid("inconsistent native tool count", 502) + this.segment.expected = count + if (this.state === "awaiting-results") return // an identical retransmission + this.waitForBatch() + this.sealBatch() + } + sealBatch() { + const segment = this.segment + if (segment.expected == null) return + if (segment.calls.length > segment.expected) invalid("native tool batch exceeded its declared count", 502) + if (segment.calls.length !== segment.expected || segment.closed) return + clearTimeout(this.batchTimer) + this.batchTimer = null + this.state = "awaiting-results" + this.batches ??= [] + this.batches.push(segment) + for (const c of segment.calls) this.pool.handles.set(c.id, { owner: this, batch: segment }) + segment.finish({ stop: "tool_calls", usage: { + prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, + prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 }, + magpie_native: { accounting: "pending" }, + } }) + this.segments++ + this.resultTimer = later(() => this.fail({ status: 410, message: "native tool-result deadline expired" }, "expired"), this.limits.resultWait) + } + store(id, data) { + if (!id.length) invalid("native blob ID is empty", 502) + const key = id.toString("hex") + if (this.knownHashes.has(key) && hash(data) !== key) invalid("native content-addressed bootstrap blob changed", 502) + const size = this.blobSize - (this.blobs.get(key)?.length ?? 0) + data.length + if (size + (this.checkpoint?.bytes.length ?? 0) > this.limits.blobBytes) invalid("native blob retention limit reached", 503) + // Incoming IDs are opaque: a fixed-root ID need not be SHA-256(data). + this.blobs.set(key, Buffer.from(data)) + this.blobSize = size + this.validateCheckpoint() + } + checkpointReceived(data) { + if (data.length + this.blobSize > this.limits.blobBytes) invalid("native checkpoint retention limit reached", 503) + nativeFields(data) + this.checkpoint = { bytes: Buffer.from(data), sequence: ++this.sequence, status: "incomplete", terminal: this.terminal } + this.validateCheckpoint() + } + validateCheckpoint() { + if (!this.checkpoint) return + const state = nativeFields(this.checkpoint.bytes) + const missing = new Set() + let supported = true + const get = (id) => { + const key = id.toString("hex") + const b = this.blobs.get(key) + if (!b) missing.add(key) + return b + } + const refs = new Set([1, 3, 6, 7, 11, 13]) + const known = new Set(Array.from({ length: 34 }, (_, i) => i + 1).filter((n) => n !== 2)) + // These shapes contain additional state/reference contracts which are not + // implemented by the caller-MCP bridge. Preserve their bytes without + // claiming reference closure or restart eligibility. + const complex = new Set([3, 6, 7, 11, 12, 13, 15, 16, 20, 24, 29, 30, 31, 32]) + for (const f of state) { + if (!known.has(f.num) || complex.has(f.num)) supported = false + if (refs.has(f.num) && f.data.length) get(f.data) + if (f.num !== 8) continue + const turn = get(f.data) + if (!turn) continue + const tf = nativeFields(turn) + const agent = field(tf, 1) + if (!agent || tf.some((f) => f.num !== 1)) { supported = false; continue } + const agentFields = nativeFields(agent.data) + if (!field(agentFields, 1)?.data.length) supported = false + for (const a of agentFields) { + if (a.num === 1) { + const user = get(a.data) + if (user) nativeFields(user) + } else if (a.num === 2) { + const step = get(a.data) + if (step) { + const sf = nativeFields(step) + if (sf.length !== 1 || ![1, 2, 3].includes(sf[0].num)) supported = false + else { + const stepFields = nativeFields(sf[0].data) + if (sf[0].num === 2 && (stepFields.length !== 1 || stepFields[0].num !== 15)) supported = false + } + } + } else if (![3, 4, 5, 6].includes(a.num)) supported = false + } + } + this.checkpoint.missing = missing.size + this.checkpoint.status = !supported ? "unsupported" : missing.size ? "incomplete" : "complete" + this.checkpoint.terminal = this.terminal + } + terminalSeen(fields) { + if (this.segment.calls.length) invalid("Cursor ended a turn with unresolved native tool calls", 502) + this.terminal = true + this.state = "finalizing" + this.usageFields = fields + if (this.checkpoint) this.checkpoint.terminal = true + clearTimeout(this.batchTimer) + this.drainTimer = later(() => { + Promise.resolve().then(() => this.complete()).catch((e) => this.fail(failureOf(e))) + }, this.limits.drain) + } + complete() { + if (this.completionTask) return this.completionTask + if (this.error || this.state === "complete") return + if (!this.terminal) invalid("native Run ended before TurnEnded or a complete final answer", 502) + const { usageOf } = this.wire + const measuredInput = this.usageFields?.some((f) => [1, 3, 4].includes(f.num)) + const measuredOutput = this.usageFields?.some((f) => f.num === 2) + const u = usageOf(this.usageFields ?? []) + if (!measuredInput) u.input = this.estimate + if (!measuredOutput) u.output = Math.floor((this.said + 3) / 4) + const prompt = u.input + u.cacheRead + u.cacheWrite + this.finalUsage = { + prompt_tokens: prompt, completion_tokens: u.output, total_tokens: prompt + u.output, + prompt_tokens_details: { cached_tokens: u.cacheRead, cache_write_tokens: u.cacheWrite }, + ...(this.usageFields?.some((f) => f.num === 5) ? { completion_tokens_details: { reasoning_tokens: u.reasoning } } : {}), + ...(!measuredInput || !measuredOutput ? { magpie_native: { accounting: "estimated" } } : {}), + } + this.state = "finalizing" + this.closeTransport() + const finish = (more) => { + if (this.error) return + const deferred = more && more.input + more.output + more.cacheRead + more.cacheWrite > 0 + this.segment.finish({ stop: "stop", usage: { + ...this.finalUsage, + ...(deferred ? { magpie_deferred: { + prompt_tokens: more.input + more.cacheRead + more.cacheWrite, + completion_tokens: more.output, + cached_tokens: more.cacheRead, + cache_write_tokens: more.cacheWrite, + } } : {}), + } }) + this.state = "complete" + this.pool.release(this) + this.replayTimer = later(() => this.pool.forget(this), this.limits.replayWait) + } + if (!this.accounting) return finish(null) + this.completionTask = this.accounting.settle().then(finish) + return this.completionTask + } + async pump(stream) { + const { pb, exec, failure } = this.wire + try { + for await (const f of stream) { + if (this.error || this.state === "complete") return + if (f.end) { + const e = failure(200, f.data) + if (e.status < 200 || e.status > 299) throw new NativeSessionError(e.status, e.message) + if (this.segment.calls.length && this.segment.expected == null) { this.missingCount(); return } + if (!this.terminal && !this.segment.calls.length && this.segment.content) this.terminalSeen([]) + await this.complete() + return + } + for (const m of nativeFields(f.data)) { + switch (m.num) { + case 1: + for (const u of nativeFields(m.data)) { + const uf = nativeFields(u.data) + if (u.num === 1 || u.num === 4) { + const text = str(uf, 1) + if (this.terminal || this.state === "awaiting-results") invalid("native output arrived outside a running Chat segment", 502) + if (text) { + this.said += text.length + if (u.num === 1) this.wrote += text.length + this.segment.emit(u.num === 1 ? { text } : { reasoning: text }) + } + } else if (u.num === 14) { + if (!this.segment.content && !this.segment.calls.length) invalid("an empty reply (Cursor ended the turn without text or a tool call)", 502) + this.terminalSeen(uf) + } else if (u.num === 27) this.listed(num(uf, 1)) + } + break + case 2: { + const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id), null, true) + if (c) this.acceptCall(c) + break + } + case 3: + this.checkpointReceived(m.data) + break + case 4: { + const kv = nativeFields(m.data) + const id = num(kv, 1) + for (const k of kv) { + if (k.num === 2) { + const want = field(nativeFields(k.data), 1)?.data.toString("hex") ?? "" + const b = this.blobs.get(want) + const res = b ? pb().bytes(1, b) : pb().bytes(2, pb().str(1, "blob not found")) + this.send(pb().bytes(3, pb().varint(1, id).bytes(2, res)).done()) + } else if (k.num === 3) { + try { + const set = nativeFields(k.data) + this.store(field(set, 1)?.data ?? Buffer.alloc(0), field(set, 2)?.data ?? Buffer.alloc(0)) + } catch (e) { + this.send(pb().bytes(3, pb().varint(1, id).bytes(3, pb().bytes(1, pb().str(1, "native blob could not be retained")))).done()) + throw e + } + this.send(pb().bytes(3, pb().varint(1, id).bytes(3, Buffer.alloc(0))).done()) + } + } + break + } + case 5: + for (const c of nativeFields(m.data)) if (c.num === 1) { + const id = num(nativeFields(c.data), 1) + const pending = this.execs.get(id) + if (pending && !pending.submitted) invalid("Cursor cancelled a pending native tool exec; late results cannot be submitted", 410) + } + break + case 7: + invalid("unsupported native interaction query", 502) + } + } + } + if (!this.error && this.state !== "complete") { + if (this.terminal) await this.complete() + else invalid("native reply broke off before completing its turn or tool batch: EOF", 502) + } + } catch (e) { + if (!this.error && this.state !== "complete") this.fail(failureOf(e)) + } + } +} + +export const nativeSessions = new NativeSessionPool() diff --git a/packages/cursor/native-session.test.mjs b/packages/cursor/native-session.test.mjs new file mode 100644 index 0000000..11d8e4b --- /dev/null +++ b/packages/cursor/native-session.test.mjs @@ -0,0 +1,203 @@ +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { EventEmitter } from "node:events" +import { _internal } from "./index.mjs" +import { NativeSessionPool, NATIVE_LIMITS, nativeFields } from "./native-session.mjs" +import { bin, text, uint, message, tool, update, setBlob, checkpoint, end, readWire, nest, number, readResult } from "./native-test-wire.mjs" + +const pools = [] +afterEach(async () => { await Promise.all(pools.splice(0).map((p) => p.clear())) }) +const registered = [{ name: "audit_echo", description: "synthetic", schema: { type: "object" }, schemaText: '{"type":"object"}' }] +const chat = (extra = {}) => ({ model: "synthetic-model", messages: [{ role: "user", content: "synthetic" }], ...extra }) +function owner(extra = {}, overrides = {}) { + const pool = new NativeSessionPool({ ...NATIVE_LIMITS, ...overrides }) + pools.push(pool) + const request = chat(extra) + const prepared = pool.prepare("synthetic-token", request, "synthetic-session", registered) + const run = pool.create(prepared, { id: "synthetic-model", maxMode: false, params: [] }, _internal) + run.chatTools = registered + const writes = [] + let closed = 0 + run.bind({ send: (b) => writes.push(Buffer.from(b)), close: () => closed++ }, new Map(), 11) + return { run, writes, pool, request, closed: () => closed } +} +const frames = (wire) => wire.map((b) => ({ data: b.subarray(5), end: !!(b[0] & 2) })) + +// H2 e2e covers the full lifecycle. These cases probe protocol fault/retention +// boundaries without depending on a network socket or the production codec. +test("native KV: failed storage replies with SetBlobResult.error, never success ACK", async () => { + const { run, writes, closed } = owner({}, { blobBytes: 8 }) + await run.pump(frames([setBlob(31, Buffer.from("opaque"), Buffer.alloc(9))])) + expect(run.error.status).toBe(503) + expect(closed()).toBe(1) + expect(writes).toHaveLength(1) + const kv = nest(writes[0], 3) + expect(number(kv, 1)).toBe(31) + const response = nest(kv, 3) + expect(readWire(response).map((f) => f.no)).toEqual([1]) + expect(run.blobs.size).toBe(0) +}) + +test("native KV: known bootstrap hashes are checked; opaque fixed-root IDs retain exact mutable bytes", async () => { + const { run } = owner() + const original = Buffer.from("synthetic original") + const id = createHash("sha256").update(original).digest() + run.knownHashes.add(id.toString("hex")) + run.store(id, original) + expect(() => run.store(id, Buffer.from("changed"))).toThrow("bootstrap blob changed") + const opaque = Buffer.from("fixed-root") + run.store(opaque, Buffer.from("first")) + run.store(opaque, Buffer.from("second")) + expect(run.blobs.get(opaque.toString("hex")).toString()).toBe("second") +}) + +test("native checkpoints: missing step/user/turn closure is never promoted, latest received state wins", () => { + const { run } = owner() + const user = Buffer.from("synthetic-user") + const turn = Buffer.from("synthetic-turn") + const step = Buffer.from("synthetic-step") + const state = bin(8, turn) + run.checkpointReceived(state) + expect(run.checkpoint.status).toBe("incomplete") + run.store(turn, bin(1, message(bin(1, user), bin(2, step)))) + expect(run.checkpoint.status).toBe("incomplete") + run.store(user, text(1, "synthetic user")) + expect(run.checkpoint.status).toBe("incomplete") + run.store(step, bin(3, text(1, "native thinking"))) + expect(run.checkpoint.status).toBe("complete") + run.checkpointReceived(bin(8, Buffer.from("new-missing-turn"))) + expect(run.checkpoint.sequence).toBe(2) + expect(run.checkpoint.status).toBe("incomplete") + run.store(Buffer.from("unrelated-late-blob"), text(1, "late")) + expect(run.checkpoint.sequence).toBe(2) + expect(run.checkpoint.status).toBe("incomplete") +}) + +test("native checkpoints: unknown/reference-bearing shapes stay retained and disable closure claims", () => { + const { run } = owner() + const state = message(bin(31, text(1, "synthetic subagent reference")), bin(99, text(1, "future state"))) + run.checkpointReceived(state) + expect(run.checkpoint.bytes).toEqual(state) + expect(run.checkpoint.status).toBe("unsupported") +}) + +test("native results: independent wire decoder sees exact text, image, explicit error flag and numeric/exec IDs", () => { + const { run } = owner() + const image = Buffer.from("89504e470d0a1a0a", "hex") + const result = run.encodeResult({ role: "tool", tool_call_id: "synthetic_call", content: [{ type: "text", text: 'Error-looking JSON: {"error":"ordinary output"}\n精确' }, { type: "image_url", image_url: { url: "data:image/png;base64," + image.toString("base64") } }], is_error: true }) + const wire = _internal.pb().bytes(2, _internal.pb().varint(1, 41).str(15, "synthetic-exec").bytes(11, result)).done() + expect(readResult(wire)).toEqual({ id: 41, execID: "synthetic-exec", isError: true, + content: [{ type: "text", text: 'Error-looking JSON: {"error":"ordinary output"}\n精确' }, { type: "image", data: image, mimeType: "image/png" }] }) + expect(readResult(_internal.pb().bytes(2, _internal.pb().varint(1, 1).bytes(11, run.encodeResult({ role: "tool", tool_call_id: "synthetic_call", content: '{"error":"success text"}' }))).done()).isError).toBe(false) +}) + +test("native protocol: changed duplicate exec and inconsistent count fail before publishing calls", async () => { + for (const kind of ["duplicate", "count"]) { + const { run } = owner() + const wire = kind === "duplicate" ? [tool(7, "synthetic-call", "first"), tool(7, "synthetic-call", "changed")] + : [update(27, uint(1, 2)), update(27, uint(1, 1))] + await run.pump(frames(wire)) + expect(run.error.status).toBe(502) + expect(run.segment.events.some((e) => e.tool)).toBe(false) + } +}) + +for (const kind of [10, 36]) test(`native protocol: repeated MCP envelopes validate before exec kind ${kind} can send a response`, () => { + const writes = [], closes = [] + const malformed = Buffer.from("08075a0c2a0a61756469745f6563686f5a030a0561", "hex") + let error + try { + _internal.exec(message(bin(kind, Buffer.alloc(0)), malformed), registered, (b) => writes.push(b), (id) => closes.push(id), null, true) + } catch (e) { error = e } + expect(error?.status).toBe(502) + expect(error?.message).toContain("truncated") + expect(writes).toEqual([]) + expect(closes).toEqual([]) +}) + +test("native protocol: malformed message tails fail explicitly, including after partial display output", async () => { + const { run } = owner() + const iterator = run.segment.iterator() + run.segment.emit({ reasoning: "synthetic partial display" }) + expect((await iterator.next()).value.reasoning).toBe("synthetic partial display") + await run.pump([{ data: Buffer.from([0x0a, 0x05, 0x01]) }]) + expect((await iterator.next()).value.error.status).toBe(502) + expect((await iterator.next()).done).toBe(true) + expect(() => nativeFields(Buffer.from([0x80]))).toThrow("malformed") +}) + +test("native admission: competing initial requests cannot overwrite a session reservation", () => { + const { pool, run, request } = owner() + const competing = { ...pool.prepare("another-account", request, "synthetic-session", registered), account: run.account, controls: run.controls } + expect(pool.create(competing, run.resolution, _internal)).toBeNull() + expect(pool.selectors.get(run.account + ":" + run.selector)).toBe(run) +}) + +test("native admission: completed replay entries are bounded; active entries are preserved", () => { + const { pool, run } = owner({}, { perAccount: 2, perProcess: 2 }) + run.terminalSeen(nativeFields(message(uint(1, 0), uint(2, 0)))) + run.complete() + for (const session of ["second", "third"]) { + const prepared = pool.prepare("synthetic-token", chat(), session, registered) + const next = pool.create(prepared, run.resolution, _internal) + if (session === "second") { + next.chatTools = registered + next.bind({ send() {}, close() {} }, new Map(), 1) + next.terminalSeen(nativeFields(message(uint(1, 0), uint(2, 0)))) + next.complete() + } + } + expect(pool.entries.size).toBe(2) + expect(pool.entries.has(run)).toBe(false) +}) + +test("native finalization: transport errors after TurnEnded fail instead of converting partial output to success", async () => { + const { run } = owner() + const error = { end: true, data: Buffer.from('{"error":{"code":"unavailable","message":"synthetic transport failure"}}') } + await run.pump([...frames([update(1, text(1, "partial final")), update(14, message(uint(1, 3), uint(2, 2)))]), error]) + expect(run.error.status).toBe(503) + expect(run.segment.events.some((e) => e.stop)).toBe(false) +}) + +test("native transport: KV, Run heartbeat and exec heartbeat share queued/in-flight admission", async () => { + const req = Object.assign(new EventEmitter(), { writable: true, destroyed: false }) + const writes = [] + req.write = (packet) => { writes.push(packet); return false } + let closed = 0 + const transport = _internal.nativeTransport(req, () => closed++, () => { throw new Error("unexpected failure") }, { outboundBytes: 1024, outboundMessages: 3 }) + const { pb } = _internal + const messages = [pb().bytes(7, Buffer.alloc(0)).done(), pb().bytes(5, pb().bytes(3, pb().varint(1, 7))).done(), pb().bytes(3, pb().varint(1, 4).bytes(2, pb().bytes(1, Buffer.from("blob")))).done()] + for (const message of messages) transport.send(message) + expect(writes).toHaveLength(1) + expect(transport.outbound).toEqual({ bytes: messages.reduce((n, b) => n + b.length + 5, 0), messages: 3 }) + expect(() => transport.send(messages[0])).toThrow("outbound messages limit") + transport.close() + await Promise.resolve() + expect(transport.outbound).toEqual({ bytes: 0, messages: 0 }) + expect(closed).toBe(1) + expect(req.listenerCount("drain")).toBe(0) + expect(req.listenerCount("close")).toBe(0) +}) + +test("native lifecycle: binding a transport after opening cancellation closes it exactly once", async () => { + const pool = new NativeSessionPool() + pools.push(pool) + const prepared = pool.prepare("synthetic-token", chat(), "synthetic-session", registered) + const run = pool.create(prepared, { id: "synthetic-model", maxMode: false, params: [] }, _internal) + await run.cancel("synthetic opening cancellation") + let closed = 0 + run.bind({ send() { throw new Error("cancelled owner wrote") }, close() { closed++ } }, new Map(), 1) + expect(closed).toBe(1) + expect(run.state).toBe("cancelled") + expect(run.runHeartbeat).toBeUndefined() + expect(run.execHeartbeat).toBeUndefined() +}) + +test("native lifecycle: absolute deadline terminates a Run even without a parked result deadline", async () => { + const { run, closed } = owner({}, { lifetime: 35 }) + const event = await run.segment.iterator().next() + expect(event.value.error.status).toBe(410) + expect(run.state).toBe("expired") + expect(closed()).toBe(1) +}) diff --git a/packages/cursor/native-test-wire.mjs b/packages/cursor/native-test-wire.mjs new file mode 100644 index 0000000..6af7876 --- /dev/null +++ b/packages/cursor/native-test-wire.mjs @@ -0,0 +1,90 @@ +// Synthetic wire fixtures, independent of the implementation's PB/fields codec. +// Field numbers follow agent.v1: no installed CLI or remote endpoint is needed. +export const vi = (value) => { + let v = BigInt(value) + const b = [] + do { + const n = Number(v & 127n) + v >>= 7n + b.push(v ? n | 128 : n) + } while (v) + return Buffer.from(b) +} +export const uint = (field, value) => Buffer.concat([vi(field * 8), vi(value)]) +export const bin = (field, value) => { + const b = Buffer.from(value) + return Buffer.concat([vi(field * 8 + 2), vi(b.length), b]) +} +export const text = (field, value) => bin(field, Buffer.from(value)) +export const message = (...parts) => Buffer.concat(parts) +export function readWire(input) { + const buffer = Buffer.from(input) + let at = 0 + const varint = () => { + let result = 0n + let shift = 0n + while (at < buffer.length) { + const b = buffer[at++] + result |= BigInt(b & 127) << shift + if (!(b & 128)) return Number(result) + shift += 7n + } + throw new Error("fixture truncated varint") + } + const out = [] + while (at < buffer.length) { + const tag = varint() + const no = tag >> 3 + const kind = tag & 7 + if (kind === 0) out.push({ no, value: varint() }) + else if (kind === 2) { + const n = varint() + if (at + n > buffer.length) throw new Error("fixture truncated bytes") + out.push({ no, data: buffer.subarray(at, at + n) }) + at += n + } else throw new Error("fixture unsupported wire") + } + return out +} +export const item = (b, n) => readWire(b).find((f) => f.no === n) +export const nest = (b, n) => { + const f = item(b, n) + if (!f?.data) throw new Error("fixture missing message " + n) + return f.data +} +export const string = (b, n) => item(b, n)?.data?.toString() ?? "" +export const number = (b, n) => item(b, n)?.value ?? 0 +export function envelope(body, flags = 0) { + const h = Buffer.alloc(5) + h[0] = flags + h.writeUInt32BE(body.length, 1) + return Buffer.concat([h, body]) +} +export const update = (n, body) => envelope(bin(1, bin(n, body))) +export const end = () => envelope(Buffer.from("{}"), 2) +export function tool(id, rawID, value = "seed", { name = "audit_echo", provider = "magpie", server = "magpie", approval = false, omitID = false, argumentValue, omitArguments = false } = {}) { + const args = omitArguments ? Buffer.alloc(0) : bin(2, message(text(1, "value"), bin(2, argumentValue ?? text(3, value)))) + const a = message(text(1, "magpie-" + name), args, text(3, rawID), text(4, provider), text(5, name), text(9, server), ...(approval ? [uint(7, 1)] : [])) + return envelope(bin(2, message(...(omitID ? [] : [uint(1, id)]), text(15, "exec-" + id), bin(11, a)))) +} +export const setBlob = (request, id, data) => envelope(bin(4, message(uint(1, request), bin(3, message(bin(1, id), bin(2, data)))))) +export const getBlob = (request, id) => envelope(bin(4, message(uint(1, request), bin(2, bin(1, id))))) +export const checkpoint = (state) => envelope(bin(3, state)) +export const abortExec = (id) => envelope(bin(5, bin(1, uint(1, id)))) +export function readResult(b) { + const exec = nest(b, 2) + const result = nest(exec, 11) + const success = nest(result, 1) + if (readWire(result).some((f) => f.no !== 1)) throw new Error("fixture expected McpResult.success") + return { + id: number(exec, 1), + execID: string(exec, 15), + content: readWire(success).filter((f) => f.no === 1).map((f) => { + const txt = item(f.data, 1) + if (txt) return { type: "text", text: string(txt.data, 1) } + const image = nest(f.data, 2) + return { type: "image", data: nest(image, 1), mimeType: string(image, 2) } + }), + isError: !!number(success, 2), + } +} diff --git a/packages/cursor/open.test.mjs b/packages/cursor/open.test.mjs index 666f0d1..674e471 100644 --- a/packages/cursor/open.test.mjs +++ b/packages/cursor/open.test.mjs @@ -6,6 +6,7 @@ import { EventEmitter, getEventListeners } from "node:events" import http2 from "node:http2" import { Duplex } from "node:stream" import { CursorAuthPlugin, _internal } from "./index.mjs" +import { NATIVE_LIMITS, nativeSessions } from "./native-session.mjs" const { open, openH1, openH2, H1, H2, fields, pb, frame, frames } = _internal const savedFetch = globalThis.fetch @@ -261,8 +262,9 @@ test("openH1: write callbacks and drain wait for serialized append response bodi expect(callbacks).toEqual([0, 1]) }) -for (const outcome of ["head abort", "completion", "HTTP error"]) { - test(`the plugin: ${outcome} releases transport ownership and its Run abort listener`, async () => { +// The same plugin ownership assertions cover retained Runs and capacity fallback. +for (const retained of [0, 32]) for (const outcome of ["head abort", "completion", "HTTP error"]) { + test(`the plugin (${retained ? "retained" : "stateless fallback"}): ${outcome} releases transport ownership and its Run abort listener`, async () => { const ac = new AbortController() const writes = [] const closed = { req: 0, session: 0, destroyed: 0 } @@ -307,10 +309,16 @@ for (const outcome of ["head abort", "completion", "HTTP error"]) { const auth = { type: "oauth", access: "synthetic-open-" + outcome, refresh: "", expires: 0 } const plugin = await CursorAuthPlugin() const loader = await plugin.auth.loader(async () => auth) - const response = await loader.fetch("http://127.0.0.1:1/v1/chat/completions", { - method: "POST", signal: ac.signal, - body: JSON.stringify({ model: "synthetic-open-model", messages: [{ role: "user", content: "synthetic request" }] }), - }) + const capacity = NATIVE_LIMITS.perProcess + let response + try { + await nativeSessions.clear() + NATIVE_LIMITS.perProcess = retained + response = await loader.fetch("http://127.0.0.1:1/v1/chat/completions", { + method: "POST", signal: ac.signal, + body: JSON.stringify({ model: "synthetic-open-model", messages: [{ role: "user", content: "synthetic request" }] }), + }) + } finally { NATIVE_LIMITS.perProcess = capacity } const result = await response.json() expect(response.status).toBe(outcome === "head abort" ? 410 : outcome === "HTTP error" ? 401 : 200) if (outcome === "head abort") { diff --git a/packages/cursor/package.json b/packages/cursor/package.json index b979259..4a73494 100644 --- a/packages/cursor/package.json +++ b/packages/cursor/package.json @@ -5,7 +5,7 @@ "type": "module", "main": "./index.mjs", "exports": "./index.mjs", - "files": ["index.mjs", "README.md"], + "files": ["index.mjs", "native-session.mjs", "README.md"], "keywords": ["opencode", "opencode-plugin", "magpie", "cursor"], "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/cursor" }