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.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
+420
-84
@@ -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 }
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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)
|
||||
})
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
})
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -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") {
|
||||
|
||||
@@ -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" }
|
||||
|
||||
Reference in New Issue
Block a user