@caph42/pi-cursor-provider 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,958 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Same-process native Run continuation.
4
+ *
5
+ * Ported from magpie's native-session.mjs (MIT):
6
+ * https://github.com/magpie-community/plugins/tree/main/packages/cursor
7
+ * Self-contained. The only import is node:crypto. Run wiring passes pb, exec,
8
+ * usageOf, and failure in. This file does not import the rest of the package.
9
+ */
10
+ import { createHash, randomBytes } from "node:crypto"
11
+
12
+ // Retention is process-local and optional. A lost owner rebuilds Chat history
13
+ // on a fresh Run; it never resubmits a result to an uncertain native exec.
14
+ // Checkpoints are retained evidence, not restart handles.
15
+ export const NATIVE_LIMITS = {
16
+ resultWait: 120_000,
17
+ lifetime: 15 * 60_000,
18
+ batchWait: 30_000,
19
+ drain: 6000,
20
+ replayWait: 120_000,
21
+ blobBytes: 64 << 20,
22
+ outputBytes: 16 << 20,
23
+ argumentBytes: 1 << 20,
24
+ argumentFields: 100_000,
25
+ argumentDepth: 64,
26
+ outboundBytes: 16 << 20,
27
+ outboundMessages: 256,
28
+ // How long a KV reply waits for room in the outbound queue (Cursor's own
29
+ // flow control taking the writes before it) before the Run fails.
30
+ writeWait: 30_000,
31
+ perAccount: 8,
32
+ perProcess: 32,
33
+ }
34
+
35
+ const HANDLE = /^call_cursor_[a-f0-9]+_\d+_\d+$/
36
+ const hash = (s) => createHash("sha256").update(s).digest("hex")
37
+ const canonical = (v) => JSON.stringify(v, (_k, x) => x && typeof x === "object" && !Array.isArray(x)
38
+ ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x)
39
+ const bytes = (v) => Buffer.byteLength(canonical(v))
40
+ const later = (fn, ms) => {
41
+ const timer = setTimeout(fn, ms)
42
+ timer.unref?.()
43
+ return timer
44
+ }
45
+
46
+ export class NativeSessionError extends Error {
47
+ constructor(status, message) {
48
+ super(message)
49
+ this.status = status
50
+ }
51
+ }
52
+ const invalid = (message, status = 409) => { throw new NativeSessionError(status, message) }
53
+ const failureOf = (e) => ({ status: e?.status ?? 502, message: e?.message ?? String(e) })
54
+
55
+ // Unlike the compatibility codec, malformed protobuf tails must fail a live
56
+ // continuation. Dropping one could turn a truncated batch into a valid handoff.
57
+ export function nativeFields(input, maxFields = Infinity) {
58
+ const b = Buffer.from(input)
59
+ const out = []
60
+ let at = 0
61
+ const uv = () => {
62
+ let n = 0
63
+ let scale = 1
64
+ for (let i = 0; i < 10 && at < b.length; i++) {
65
+ const c = b[at++]
66
+ n += (c & 127) * scale
67
+ if (c < 128 && Number.isSafeInteger(n)) return n
68
+ scale *= 128
69
+ }
70
+ invalid("malformed native protobuf", 502)
71
+ }
72
+ while (at < b.length) {
73
+ const key = uv()
74
+ const num = Math.floor(key / 8)
75
+ const wire = key % 8
76
+ if (!num || num > 0x1fffffff) invalid("malformed native protobuf field", 502)
77
+ let n = 0
78
+ let data = Buffer.alloc(0)
79
+ if (wire === 0) n = uv()
80
+ else if (wire === 2 || wire === 1 || wire === 5) {
81
+ const size = wire === 2 ? uv() : wire === 1 ? 8 : 4
82
+ if (at + size > b.length) invalid("truncated native protobuf", 502)
83
+ data = b.subarray(at, at + size)
84
+ at += size
85
+ } else invalid("unsupported native protobuf wire type", 502)
86
+ if (out.length >= maxFields) invalid("native protobuf field limit reached", 502)
87
+ out.push({ num, wire, n, data })
88
+ }
89
+ return out
90
+ }
91
+ // Decode every known Value kind, including overwritten oneof/map fields, so
92
+ // corrupt bytes cannot become different, valid JSON through prefix decoding.
93
+ // Missing scalar/map values keep protobuf defaults; unknown fields are skipped
94
+ // only after their complete wire envelope has passed validation.
95
+ export function nativeMcpArgs(input, limits = NATIVE_LIMITS) {
96
+ if (input.length > limits.argumentBytes) invalid("native MCP argument byte limit reached", 502)
97
+ let remaining = limits.argumentFields
98
+ const read = (b) => {
99
+ const fs = nativeFields(b, remaining)
100
+ remaining -= fs.length
101
+ return fs
102
+ }
103
+ const typed = (f, wire) => {
104
+ if (f.wire !== wire) invalid("invalid native MCP argument field type", 502)
105
+ }
106
+ const utf8 = (b) => {
107
+ try { return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(b) }
108
+ catch { invalid("invalid UTF-8 in native MCP arguments", 502) }
109
+ }
110
+ function mapEntry(b, depth) {
111
+ let key = "", value = null
112
+ for (const f of read(b)) {
113
+ if (f.num === 1) { typed(f, 2); key = utf8(f.data) }
114
+ else if (f.num === 2) { typed(f, 2); value = decodeValue(f.data, depth) }
115
+ }
116
+ return [key, value]
117
+ }
118
+ function decodeStruct(b, depth) {
119
+ const entries = []
120
+ for (const f of read(b)) if (f.num === 1) {
121
+ typed(f, 2)
122
+ entries.push(mapEntry(f.data, depth))
123
+ }
124
+ return Object.fromEntries(entries)
125
+ }
126
+ function decodeValue(b, depth = 0) {
127
+ if (depth > limits.argumentDepth) invalid("native MCP argument nesting limit reached", 502)
128
+ let value = null
129
+ for (const f of read(b)) {
130
+ if (f.num < 1 || f.num > 6) continue
131
+ typed(f, [0, 1, 2, 0, 2, 2][f.num - 1])
132
+ switch (f.num) {
133
+ case 1:
134
+ if (f.n !== 0) invalid("invalid native protobuf NullValue", 502)
135
+ value = null
136
+ break
137
+ case 2:
138
+ value = f.data.readDoubleLE(0)
139
+ if (!Number.isFinite(value)) invalid("nonfinite native MCP argument number", 502)
140
+ break
141
+ case 3: value = utf8(f.data); break
142
+ case 4: value = f.n !== 0; break
143
+ case 5: value = decodeStruct(f.data, depth + 1); break
144
+ case 6:
145
+ value = []
146
+ for (const item of read(f.data)) if (item.num === 1) {
147
+ typed(item, 2)
148
+ value.push(decodeValue(item.data, depth + 1))
149
+ }
150
+ break
151
+ }
152
+ }
153
+ return value
154
+ }
155
+ const fs = read(input), entries = []
156
+ for (const f of fs) {
157
+ if ([1, 3, 4, 5, 9].includes(f.num)) { typed(f, 2); utf8(f.data) }
158
+ else if (f.num === 2) { typed(f, 2); entries.push(mapEntry(f.data, 0)) }
159
+ else if (f.num === 6) typed(f, 2)
160
+ else if (f.num === 7) typed(f, 0)
161
+ }
162
+ return { fields: fs, args: Object.fromEntries(entries) }
163
+ }
164
+
165
+ const field = (fs, n) => fs.find((f) => f.num === n)
166
+ const str = (fs, n) => field(fs, n)?.data.toString("utf8") ?? ""
167
+ const num = (fs, n) => field(fs, n)?.n ?? 0
168
+
169
+ function argsOf(s) {
170
+ try {
171
+ const v = typeof s === "string" ? JSON.parse(s) : s
172
+ if (v && typeof v === "object" && !Array.isArray(v)) return v
173
+ } catch {}
174
+ invalid("invalid tool arguments in native continuation", 400)
175
+ }
176
+ // These conversions only decide whether a retained exec can be continued.
177
+ // Unsupported parts make that request use the legacy history builder instead
178
+ // of imposing a new Chat request contract on all callers.
179
+ function assistantDisplay(message) {
180
+ const parts = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content ?? []
181
+ if (!Array.isArray(parts) || parts.some((p) => !["text", "reasoning"].includes(p?.type) || typeof p.text !== "string")) invalid("unsupported native assistant display")
182
+ const reasoning = [message.reasoning_content, message.reasoning, message.reasoning_text].find((v) => typeof v === "string" && v.trim()) ?? ""
183
+ return {
184
+ text: parts.filter((p) => p.type === "text").map((p) => p.text).join(""),
185
+ reasoning: reasoning + parts.filter((p) => p.type === "reasoning").map((p) => p.text).join(""),
186
+ }
187
+ }
188
+ function resultParts(message, limits) {
189
+ const parts = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content
190
+ if (!Array.isArray(parts)) invalid("unsupported native tool result")
191
+ let retained = 0
192
+ return parts.map((part) => {
193
+ if (part?.type === "text" && typeof part.text === "string") {
194
+ retained += Buffer.byteLength(part.text)
195
+ if (retained > limits.outputBytes) invalid("native tool result limit reached")
196
+ return { text: part.text }
197
+ }
198
+ const url = part?.type === "image_url" ? (typeof part.image_url === "string" ? part.image_url : part.image_url?.url)
199
+ : part?.type === "image" && part.source?.type === "base64" ? `data:${part.source.media_type};base64,${part.source.data}` : ""
200
+ const image = /^data:(image\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/]*={0,2})$/.exec(url ?? "")
201
+ if (!image) invalid("unsupported native tool result content")
202
+ const data = Buffer.from(image[2], "base64")
203
+ retained += data.length
204
+ if (retained > limits.outputBytes) invalid("native tool result limit reached")
205
+ if (!data.length || data.toString("base64").replace(/=+$/, "") !== image[2].replace(/=+$/, "")) invalid("invalid native result image")
206
+ return { data, mimeType: image[1] }
207
+ })
208
+ }
209
+ function normalizeMessage(m) {
210
+ if (m?.role !== "assistant") return m
211
+ const { text, reasoning } = assistantDisplay(m)
212
+ const out = { ...m, content: text }
213
+ delete out.reasoning
214
+ delete out.reasoning_content
215
+ delete out.reasoning_text
216
+ if (reasoning) out.reasoning_content = reasoning
217
+ if (m.tool_calls) out.tool_calls = m.tool_calls.map((c) => ({
218
+ ...c, type: c.type ?? "function", function: { ...c.function, arguments: argsOf(c.function?.arguments ?? "{}") },
219
+ }))
220
+ return out
221
+ }
222
+ const historyDigest = (messages) => hash(canonical(messages.map(normalizeMessage)))
223
+ function controlsOf(chat, selector, tools) {
224
+ const controls = { ...chat }
225
+ for (const k of ["messages", "stream", "stream_options"]) delete controls[k]
226
+ return hash(canonical({ selector, controls, tools }))
227
+ }
228
+ const toolAttachment = (m) => m?.role === "user" && Array.isArray(m.content) && m.content.length > 1
229
+ && m.content[0]?.type === "text" && m.content[0].text === "Attached image(s) from tool result:"
230
+ && m.content.slice(1).every((p) => p?.type === "image_url")
231
+ // A complete result batch is validated before reserving or writing any exec.
232
+ // Only the current exported assistant may omit display reasoning. All earlier
233
+ // accepted history must match, including instruction order and attachments.
234
+ function matchResults(batch, messages) {
235
+ if (historyDigest(messages.slice(0, batch.prefixLength)) !== batch.prefixDigest) invalid("native continuation history diverged")
236
+ const suffix = messages.slice(batch.prefixLength)
237
+ const assistants = []
238
+ while (suffix[assistants.length]?.role === "assistant") assistants.push(suffix[assistants.length])
239
+ if (!assistants.length) invalid("native continuation is missing its assistant tool calls", 400)
240
+ let content = ""
241
+ let reasoning = ""
242
+ const calls = []
243
+ for (const m of assistants) {
244
+ const unknown = Object.keys(m).filter((k) => !["role", "content", "tool_calls", "reasoning", "reasoning_content", "reasoning_text"].includes(k))
245
+ if (unknown.length) invalid("unsupported assistant fields in native continuation", 400)
246
+ const display = assistantDisplay(m)
247
+ content += display.text
248
+ reasoning += display.reasoning
249
+ for (const c of m.tool_calls ?? []) {
250
+ if (c.type && c.type !== "function") invalid("unsupported native continuation tool call", 400)
251
+ calls.push({ id: c.id, name: c.function?.name, args: argsOf(c.function?.arguments ?? "{}") })
252
+ }
253
+ }
254
+ if (content !== batch.content || reasoning && reasoning !== batch.reasoning) invalid("native continuation assistant output changed")
255
+ const expected = batch.calls.map((c) => ({ id: c.id, name: c.name, args: argsOf(c.args) }))
256
+ const sorted = (v) => [...v].sort((a, b) => String(a.id).localeCompare(String(b.id)))
257
+ if (canonical(sorted(calls)) !== canonical(sorted(expected))) invalid("native continuation tool calls changed")
258
+ let results = suffix.slice(assistants.length)
259
+ // Pi's exact image suffix has no call IDs. Only a single complete result
260
+ // gives it unambiguous ownership; all other shapes rebuild legacy history.
261
+ if (batch.calls.length === 1 && results.length === 2 && results[0]?.role === "tool" && toolAttachment(results[1])) {
262
+ const [result, attachment] = results
263
+ const content = typeof result.content === "string" ? [{ type: "text", text: result.content }] : result.content
264
+ if (!Array.isArray(content)) invalid("unsupported native tool result")
265
+ results = [{ ...result, content: [...content, ...attachment.content.slice(1)] }]
266
+ }
267
+ if (results.some((m) => m?.role !== "tool")) invalid("new input cannot be interleaved with pending native results")
268
+ const ids = new Set()
269
+ for (const m of results) {
270
+ if (ids.has(m.tool_call_id)) invalid("duplicate native tool result", 400)
271
+ ids.add(m.tool_call_id)
272
+ if (!expected.some((c) => c.id === m.tool_call_id)) invalid("unknown native tool result", 400)
273
+ }
274
+ if (ids.size !== expected.length) invalid("all parallel native tool results must be submitted together", 400)
275
+ return [...results].sort((a, b) => a.tool_call_id.localeCompare(b.tool_call_id))
276
+ }
277
+
278
+ class Segment {
279
+ constructor(owner, chat) {
280
+ this.owner = owner
281
+ this.prefixLength = chat.messages.length
282
+ this.prefixDigest = historyDigest(chat.messages)
283
+ this.events = []
284
+ this.calls = []
285
+ // answered: the step's execs the bridge answered itself (a refusal, or
286
+ // the MCP tool list). Cursor's tool_requests_listed counts them too.
287
+ this.answered = 0
288
+ this.content = ""
289
+ this.reasoning = ""
290
+ this.expected = null
291
+ this.closed = false
292
+ this.clean = false
293
+ this.waiters = new Set()
294
+ }
295
+ wake() {
296
+ for (const wake of this.waiters) wake()
297
+ this.waiters.clear()
298
+ }
299
+ emit(e) {
300
+ this.owner.retain(bytes(e))
301
+ if (e.text) this.content += e.text
302
+ if (e.reasoning) this.reasoning += e.reasoning
303
+ this.events.push(e)
304
+ this.wake()
305
+ }
306
+ finish(stop) {
307
+ for (const [index, c] of this.calls.entries()) {
308
+ const e = { tool: { index, id: c.id, name: c.name, args: c.args } }
309
+ this.owner.retain(bytes(e))
310
+ this.events.push(e)
311
+ }
312
+ this.owner.retain(bytes(stop))
313
+ this.events.push(stop)
314
+ this.closed = true
315
+ this.wake()
316
+ }
317
+ fail(error) {
318
+ // Errors also override a sealed, as yet undelivered handoff.
319
+ this.events = [{ error }]
320
+ this.closed = true
321
+ this.wake()
322
+ }
323
+ iterator({ replay = false } = {}) {
324
+ const segment = this
325
+ let at = 0
326
+ let errorSent = false
327
+ return {
328
+ async next() {
329
+ while (!segment.closed && at >= segment.events.length) await new Promise((r) => segment.waiters.add(r))
330
+ if (!replay && segment.owner.error) {
331
+ if (errorSent) return { done: true }
332
+ errorSent = true
333
+ return { value: { error: segment.owner.error }, done: false }
334
+ }
335
+ if (at < segment.events.length) {
336
+ const event = segment.events[at++]
337
+ if (replay && event.stop) return { value: { ...event, usage: {
338
+ prompt_tokens: 0, completion_tokens: 0, total_tokens: 0,
339
+ prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 },
340
+ magpie_native: { accounting: "replayed" },
341
+ } }, done: false }
342
+ return { value: event, done: false }
343
+ }
344
+ return { done: true }
345
+ },
346
+ async return() {
347
+ if (!replay) await segment.owner.cancel("the Chat response was cancelled")
348
+ return { done: true }
349
+ },
350
+ [Symbol.asyncIterator]() { return this },
351
+ }
352
+ }
353
+ }
354
+
355
+ export class NativeSessionPool {
356
+ constructor(limits = NATIVE_LIMITS) {
357
+ this.limits = limits
358
+ this.entries = new Set()
359
+ this.handles = new Map()
360
+ this.selectors = new Map()
361
+ }
362
+ // selector is conversationID(chat, session): session/cache key AND first
363
+ // user identity. Task subagents sharing a session must not own its parent.
364
+ prepare(tok, chat, selector, tools) {
365
+ const fallback = (reason) => ({ fallback: reason })
366
+ if (!Array.isArray(chat.messages) || bytes(chat) > this.limits.outputBytes) return fallback("history retention limit")
367
+ const account = hash(tok)
368
+ const controls = controlsOf(chat, selector, tools)
369
+ const trailing = []
370
+ const end = chat.messages.length - (toolAttachment(chat.messages.at(-1)) ? 2 : 1)
371
+ for (let i = end; i >= 0 && chat.messages[i]?.role === "tool"; i--) trailing.push(chat.messages[i].tool_call_id)
372
+ const handles = trailing.filter((id) => typeof id === "string" && HANDLE.test(id))
373
+ if (handles.length) {
374
+ // Look up ownership before inspecting native history. Restarted callers
375
+ // only need the same permissive history shape the stateless path accepts.
376
+ const found = handles.map((id) => this.handles.get(id))
377
+ if (found.some((v) => !v)) return fallback("owner unavailable")
378
+ const { owner, batch } = found[0]
379
+ if (found.some((v) => v.owner !== owner || v.batch !== batch)) return fallback("different native batches")
380
+ if (owner.account !== account || owner.controls !== controls || owner.error) return fallback("owner incompatible or expired")
381
+ try {
382
+ const results = matchResults(batch, chat.messages)
383
+ // Encoding is pure for the entire batch before any reservation or write.
384
+ const encoded = results.map((m) => owner.encodeResult(m))
385
+ const digest = hash(canonical(results))
386
+ if (batch.resultDigest) {
387
+ // An uncertain or concurrent write is never submitted twice to this
388
+ // exec. History reconstruction uses provided results as imported data.
389
+ if (batch.resultDigest !== digest || !batch.next?.clean) return fallback("result already submitted or busy")
390
+ return { owner, batch, replay: true, segment: batch.next }
391
+ }
392
+ if (owner.state !== "awaiting-results" || owner.segment !== batch || !batch.clean) return fallback("owner busy")
393
+ // A retained Run's absolute timer spans all tool roundtrips. Rebuild
394
+ // near its deadline before writing this batch: otherwise a new Chat
395
+ // segment can lose its transport after already exposing output.
396
+ const reserve = Math.min(60_000, owner.limits.lifetime / 10)
397
+ if (owner.expiresAt - Date.now() <= reserve) {
398
+ owner.fail({ status: 410, message: "native Run retired before lifetime deadline" }, "expired")
399
+ return fallback("owner near lifetime deadline")
400
+ }
401
+ return { owner, batch, results, encoded, digest, chat }
402
+ } catch (e) {
403
+ if (!(e instanceof NativeSessionError)) throw e
404
+ return fallback("history incompatible with retained owner")
405
+ }
406
+ }
407
+ // Pending ancestors, new input, and terminal old handles are ordinary
408
+ // imported history, even while a parent Run is still awaiting its results.
409
+ if (chat.messages.some((m) => m?.tool_calls?.some((c) => HANDLE.test(c?.id ?? "")))) return fallback("historical native calls")
410
+ if (selector && this.selectors.has(account + ":" + selector)) return fallback("owner busy")
411
+ return { account, selector, controls, selected: !!selector, chat }
412
+ }
413
+ create(prepared, resolution, wire) {
414
+ if (prepared.fallback || prepared.selected && this.selectors.has(prepared.account + ":" + prepared.selector)) return null
415
+ const crowded = () => this.entries.size >= this.limits.perProcess || [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
416
+ while (crowded()) {
417
+ const accountFull = [...this.entries].filter((e) => e.account === prepared.account).length >= this.limits.perAccount
418
+ const finished = [...this.entries].find((e) => ["complete", "failed", "cancelled", "expired"].includes(e.state) && (!accountFull || e.account === prepared.account))
419
+ if (!finished) return null
420
+ this.forget(finished)
421
+ }
422
+ let owner
423
+ try { owner = new NativeSession(this, prepared, resolution, wire) }
424
+ catch (e) {
425
+ if (!(e instanceof NativeSessionError)) throw e
426
+ return null
427
+ }
428
+ this.entries.add(owner)
429
+ if (prepared.selected) this.selectors.set(owner.account + ":" + owner.selector, owner)
430
+ return owner
431
+ }
432
+ release(owner) {
433
+ const key = owner.account + ":" + owner.selector
434
+ if (this.selectors.get(key) === owner) this.selectors.delete(key)
435
+ }
436
+ forget(owner) {
437
+ owner.accounting?.abandon()
438
+ clearTimeout(owner.replayTimer)
439
+ this.release(owner)
440
+ this.entries.delete(owner)
441
+ for (const [id, h] of this.handles) if (h.owner === owner) this.handles.delete(id)
442
+ owner.blobs.clear()
443
+ owner.checkpoint = null
444
+ owner.execs.clear()
445
+ owner.nativeCalls.clear()
446
+ }
447
+ async clear() {
448
+ await Promise.all([...this.entries].map((e) => e.cancel("native owner removed")))
449
+ for (const e of this.entries) {
450
+ clearTimeout(e.replayTimer)
451
+ this.forget(e)
452
+ }
453
+ }
454
+ }
455
+
456
+ class NativeSession {
457
+ constructor(pool, prepared, resolution, wire) {
458
+ Object.assign(this, prepared)
459
+ this.pool = pool
460
+ this.limits = pool.limits
461
+ this.resolution = resolution
462
+ this.wire = wire
463
+ this.identity = randomBytes(12).toString("hex")
464
+ this.state = "opening"
465
+ this.ac = new AbortController()
466
+ this.execs = new Map()
467
+ this.nativeCalls = new Map()
468
+ this.blobs = new Map()
469
+ this.knownHashes = new Set()
470
+ this.blobSize = 0
471
+ this.retainedBytes = 0
472
+ this.sequence = 0
473
+ this.segments = 0
474
+ // the model calls of the turn so far, and what was said before the
475
+ // latest one began: the last step's own share of the turn (#156)
476
+ this.steps = 1
477
+ this.stepSaid = 0
478
+ this.said = 0
479
+ this.wrote = 0
480
+ this.terminal = false
481
+ this.segment = new Segment(this, prepared.chat)
482
+ this.retain(bytes(prepared.chat))
483
+ this.expireIn(this.limits.lifetime)
484
+ }
485
+ // expireIn sets the Run's absolute deadline ms from now: from its start,
486
+ // the whole lifetime; a test brings it in after the first answer
487
+ expireIn(ms) {
488
+ clearTimeout(this.lifetimeTimer)
489
+ this.expiresAt = Date.now() + ms
490
+ this.lifetimeTimer = later(() => this.fail({ status: 410, message: "native Run lifetime expired" }, "expired"), ms)
491
+ }
492
+ retain(n) {
493
+ if (this.retainedBytes + n > this.limits.outputBytes) invalid("native output/history retention limit reached", 503)
494
+ this.retainedBytes += n
495
+ }
496
+ attach(signal, segment = this.segment) {
497
+ if (signal?.aborted) {
498
+ this.fail({ status: 410, message: "the Chat request was already cancelled" }, "cancelled")
499
+ return
500
+ }
501
+ const abort = () => this.fail({ status: 410, message: "the Chat request was cancelled" }, "cancelled")
502
+ signal?.addEventListener("abort", abort, { once: true })
503
+ segment.detach = () => signal?.removeEventListener("abort", abort)
504
+ }
505
+ delivered(segment = this.segment) {
506
+ if (this.error) return
507
+ segment.clean = true
508
+ segment.detach?.()
509
+ if (this.state === "complete" && segment === this.segment) this.accounting?.delivered()
510
+ }
511
+ closeTransport() {
512
+ if (this.transportClosed) return
513
+ this.transportClosed = true
514
+ clearInterval(this.runHeartbeat)
515
+ clearInterval(this.execHeartbeat)
516
+ clearTimeout(this.batchTimer)
517
+ clearTimeout(this.resultTimer)
518
+ clearTimeout(this.drainTimer)
519
+ clearTimeout(this.lifetimeTimer)
520
+ this.ac.abort()
521
+ this.transport?.close()
522
+ }
523
+ fail(error, state = "failed") {
524
+ if (this.error || this.state === "complete") return
525
+ this.error = error
526
+ this.state = state
527
+ this.segment.fail(error)
528
+ for (const segment of this.batches ?? []) segment.detach?.()
529
+ this.segment.detach?.()
530
+ this.closeTransport()
531
+ // A failed transport has no reusable execs. Forget its handles immediately;
532
+ // subsequent caller-supplied history takes the stateless path.
533
+ this.pool.forget(this)
534
+ }
535
+ async cancel(message) {
536
+ this.fail({ status: 410, message }, "cancelled")
537
+ await this.pumpTask
538
+ }
539
+ bind(transport, blobs, estimate) {
540
+ if (this.transportClosed || this.error) {
541
+ transport.close()
542
+ return
543
+ }
544
+ this.transport = transport
545
+ this.estimate = estimate
546
+ this.stepEstimate = estimate
547
+ this.blobs = blobs
548
+ this.knownHashes = new Set(blobs.keys())
549
+ this.blobSize = [...blobs.values()].reduce((n, b) => n + b.length, 0)
550
+ if (this.blobSize > this.limits.blobBytes) invalid("native bootstrap blob limit reached", 503)
551
+ if (this.error) return this.closeTransport()
552
+ this.state = "running"
553
+ const { pb } = this.wire
554
+ const heartbeat = (message) => {
555
+ try { this.send(message) } catch (e) { this.fail(failureOf(e)) }
556
+ }
557
+ this.runHeartbeat = setInterval(() => heartbeat(pb().bytes(7, Buffer.alloc(0)).done()), 5000)
558
+ this.execHeartbeat = setInterval(() => {
559
+ for (const c of this.execs.values()) if (!c.submitted) heartbeat(pb().bytes(5, pb().bytes(3, pb().varint(1, c.requestID))).done())
560
+ }, 3000)
561
+ this.runHeartbeat.unref?.()
562
+ this.execHeartbeat.unref?.()
563
+ }
564
+ send(message) {
565
+ if (this.error || this.transportClosed) invalid("native transport is no longer writable", 410)
566
+ this.transport.send(message)
567
+ }
568
+ // reply answers one of Cursor's KV requests once the outbound queue has
569
+ // room. Cursor asks for every history blob at once, hundreds for a long
570
+ // conversation, faster than a slow link takes the replies: the decoder
571
+ // waits for the queue rather than failing the Run (#142).
572
+ async reply(message) {
573
+ await this.transport.room?.(message.length + 5)
574
+ this.send(message)
575
+ }
576
+ execClose(id) {
577
+ this.send(this.wire.pb().bytes(5, this.wire.pb().bytes(1, this.wire.pb().varint(1, id))).done())
578
+ }
579
+ encodeResult(message) {
580
+ const { pb } = this.wire
581
+ const success = pb()
582
+ for (const item of resultParts(message, this.limits)) {
583
+ if (item.text !== undefined) success.bytes(1, pb().bytes(1, pb().str(1, item.text)))
584
+ else success.bytes(1, pb().bytes(2, pb().bytes(1, item.data).str(2, item.mimeType)))
585
+ }
586
+ if (message.is_error === true || message.isError === true) success.varint(2, 1)
587
+ return pb().bytes(1, success).done() // McpResult.success, not stored McpToolResult
588
+ }
589
+ resume(prepared, signal) {
590
+ if (prepared.replay) return this.response(prepared.segment, true)
591
+ const batch = prepared.batch
592
+ if (this.error || this.state !== "awaiting-results" || this.segment !== batch || batch.resultDigest) invalid("native continuation is already reserved")
593
+ const next = new Segment(this, prepared.chat)
594
+ this.attach(signal, next)
595
+ if (this.error) invalid(this.error.message, this.error.status)
596
+ // Reserve synchronously. Competing continuations cannot interleave writes.
597
+ batch.resultDigest = prepared.digest
598
+ batch.next = next
599
+ this.segment = next
600
+ this.state = "submitting"
601
+ clearTimeout(this.resultTimer)
602
+ clearTimeout(this.batchTimer)
603
+ this.batchTimer = null
604
+ this.nextStep(prepared.estimate)
605
+ try {
606
+ for (let i = 0; i < prepared.results.length; i++) {
607
+ const call = batch.calls.find((c) => c.id === prepared.results[i].tool_call_id)
608
+ const msg = this.wire.pb().varint(1, call.requestID)
609
+ if (call.execID) msg.str(15, call.execID)
610
+ msg.bytes(11, prepared.encoded[i])
611
+ this.resultSubmitted = true
612
+ this.send(this.wire.pb().bytes(2, msg).done())
613
+ call.submitted = true
614
+ this.execClose(call.requestID)
615
+ }
616
+ this.state = "running"
617
+ } catch (e) {
618
+ const error = failureOf(e)
619
+ this.fail({ status: error.status, message: `${error.message}; native result submission failed; its outcome is uncertain and cannot be replayed` })
620
+ }
621
+ return this.response(next)
622
+ }
623
+ response(segment = this.segment, replay = false) {
624
+ return {
625
+ events: segment.iterator({ replay }),
626
+ cancel: () => replay ? Promise.resolve() : this.cancel("the Chat response was cancelled"),
627
+ resolution: this.resolution,
628
+ delivered: () => replay || this.delivered(segment),
629
+ diagnostic: `same-run; bootstrap=imported-history; new-turn=stateless; missing-owner=stateless${replay ? "; replay=true" : ""}`,
630
+ }
631
+ }
632
+ acceptCall(call) {
633
+ if (!Number.isInteger(call.requestID)) invalid("native tool call is missing its exec request ID", 502)
634
+ const prior = this.execs.get(call.requestID)
635
+ const digest = hash(canonical({ requestID: call.requestID, execID: call.execID, nativeID: call.nativeID, name: call.name, args: argsOf(call.args) }))
636
+ if (prior) {
637
+ if (prior.digest !== digest) invalid("native exec identity changed during retransmission", 502)
638
+ return
639
+ }
640
+ // A retransmission of the final exec can arrive after it sealed its batch.
641
+ // Validate that identity first; only a new exec violates the sealed phase.
642
+ if (this.terminal || this.state === "awaiting-results") invalid("native call arrived after its batch was sealed", 502)
643
+ if (call.nativeID && this.nativeCalls.has(call.nativeID)) invalid("native tool-call ID was reused for another exec", 502)
644
+ call.id = `call_cursor_${this.identity}_${this.segments}_${this.segment.calls.length}`
645
+ call.digest = digest
646
+ this.execs.set(call.requestID, call)
647
+ if (call.nativeID) this.nativeCalls.set(call.nativeID, call)
648
+ this.segment.calls.push(call)
649
+ this.retain(bytes(call))
650
+ this.said += call.args.length
651
+ this.waitForBatch()
652
+ this.sealBatch()
653
+ }
654
+ // nextStep is Cursor's next model call in the same turn: after the
655
+ // caller's results, or after a step whose calls were all answered here.
656
+ nextStep(estimate) {
657
+ this.steps++
658
+ this.stepSaid = this.said
659
+ if (estimate != null) this.stepEstimate = estimate
660
+ }
661
+ // waitForBatch gives the step batchWait from its latest call, answered
662
+ // call or count, not from its first. Cursor sends each call once the model
663
+ // has written its arguments, so a step of many long calls arrives over
664
+ // longer than batchWait while never pausing that long (#155).
665
+ waitForBatch() {
666
+ clearTimeout(this.batchTimer)
667
+ this.batchTimer = later(() => {
668
+ if (this.segment.expected == null && this.segment.calls.length && !this.resultSubmitted) this.missingCount()
669
+ else this.fail({ status: 502, message: "Cursor did not complete its declared native tool batch" })
670
+ }, this.limits.batchWait)
671
+ }
672
+ missingCount() {
673
+ this.fail({ status: 502, message: "Cursor did not declare its native tool batch", retentionIneligible: !this.resultSubmitted })
674
+ }
675
+ // A call of the model's step the bridge answered itself: a refused tool (a
676
+ // name it doesn't serve, Cursor's own tools) or get_mcp_tools. Cursor's
677
+ // count is of every call the step made, so it counts toward the batch;
678
+ // never handed to the caller (#142).
679
+ answeredCall() {
680
+ if (this.terminal || this.state === "awaiting-results") return
681
+ this.segment.answered++
682
+ if (this.batchTimer) this.waitForBatch()
683
+ this.sealBatch()
684
+ }
685
+ listed(count) {
686
+ if (!Number.isSafeInteger(count) || count < 1) invalid("invalid native tool count", 502)
687
+ if (this.segment.expected != null && this.segment.expected !== count) {
688
+ // Conflicting counts leave the native step boundary ambiguous. Retire
689
+ // this owner; Chat may rebuild from history only if no native result
690
+ // was submitted to this Run.
691
+ this.fail({ status: 502, message: "inconsistent native tool count", retentionIneligible: !this.resultSubmitted, continuityReason: "inconsistent-batch-count" })
692
+ return
693
+ }
694
+ this.segment.expected = count
695
+ if (this.state === "awaiting-results") return // an identical retransmission
696
+ this.waitForBatch()
697
+ this.sealBatch()
698
+ }
699
+ sealBatch() {
700
+ const segment = this.segment
701
+ if (segment.expected == null) return
702
+ const made = segment.calls.length + segment.answered
703
+ if (made > segment.expected) invalid("native tool batch exceeded its declared count", 502)
704
+ if (made !== segment.expected || segment.closed) return
705
+ if (!segment.calls.length) {
706
+ // Every call of the step was answered here: Cursor goes on with the
707
+ // turn by itself, and its next step lists a count of its own.
708
+ segment.expected = null
709
+ segment.answered = 0
710
+ clearTimeout(this.batchTimer)
711
+ this.batchTimer = null
712
+ this.nextStep()
713
+ return
714
+ }
715
+ clearTimeout(this.batchTimer)
716
+ this.batchTimer = null
717
+ this.state = "awaiting-results"
718
+ this.batches ??= []
719
+ this.batches.push(segment)
720
+ for (const c of segment.calls) this.pool.handles.set(c.id, { owner: this, batch: segment })
721
+ segment.finish({ stop: "tool_calls", usage: {
722
+ prompt_tokens: 0, completion_tokens: 0, total_tokens: 0,
723
+ prompt_tokens_details: { cached_tokens: 0, cache_write_tokens: 0 },
724
+ magpie_native: { accounting: "pending" },
725
+ } })
726
+ this.segments++
727
+ this.resultTimer = later(() => this.fail({ status: 410, message: "native tool-result deadline expired" }, "expired"), this.limits.resultWait)
728
+ }
729
+ store(id, data) {
730
+ if (!id.length) invalid("native blob ID is empty", 502)
731
+ const key = id.toString("hex")
732
+ if (this.knownHashes.has(key) && hash(data) !== key) invalid("native content-addressed bootstrap blob changed", 502)
733
+ const size = this.blobSize - (this.blobs.get(key)?.length ?? 0) + data.length
734
+ if (size + (this.checkpoint?.bytes.length ?? 0) > this.limits.blobBytes) invalid("native blob retention limit reached", 503)
735
+ // Incoming IDs are opaque: a fixed-root ID need not be SHA-256(data).
736
+ this.blobs.set(key, Buffer.from(data))
737
+ this.blobSize = size
738
+ this.validateCheckpoint()
739
+ }
740
+ checkpointReceived(data) {
741
+ if (data.length + this.blobSize > this.limits.blobBytes) invalid("native checkpoint retention limit reached", 503)
742
+ nativeFields(data)
743
+ this.checkpoint = { bytes: Buffer.from(data), sequence: ++this.sequence, status: "incomplete", terminal: this.terminal }
744
+ this.validateCheckpoint()
745
+ }
746
+ validateCheckpoint() {
747
+ if (!this.checkpoint) return
748
+ const state = nativeFields(this.checkpoint.bytes)
749
+ const missing = new Set()
750
+ let supported = true
751
+ const get = (id) => {
752
+ const key = id.toString("hex")
753
+ const b = this.blobs.get(key)
754
+ if (!b) missing.add(key)
755
+ return b
756
+ }
757
+ const refs = new Set([1, 3, 6, 7, 11, 13])
758
+ const known = new Set(Array.from({ length: 34 }, (_, i) => i + 1).filter((n) => n !== 2))
759
+ // These shapes contain additional state/reference contracts which are not
760
+ // implemented by the caller-MCP bridge. Preserve their bytes without
761
+ // claiming reference closure or restart eligibility.
762
+ const complex = new Set([3, 6, 7, 11, 12, 13, 15, 16, 20, 24, 29, 30, 31, 32])
763
+ for (const f of state) {
764
+ if (!known.has(f.num) || complex.has(f.num)) supported = false
765
+ if (refs.has(f.num) && f.data.length) get(f.data)
766
+ if (f.num !== 8) continue
767
+ const turn = get(f.data)
768
+ if (!turn) continue
769
+ const tf = nativeFields(turn)
770
+ const agent = field(tf, 1)
771
+ if (!agent || tf.some((f) => f.num !== 1)) { supported = false; continue }
772
+ const agentFields = nativeFields(agent.data)
773
+ if (!field(agentFields, 1)?.data.length) supported = false
774
+ for (const a of agentFields) {
775
+ if (a.num === 1) {
776
+ const user = get(a.data)
777
+ if (user) nativeFields(user)
778
+ } else if (a.num === 2) {
779
+ const step = get(a.data)
780
+ if (step) {
781
+ const sf = nativeFields(step)
782
+ if (sf.length !== 1 || ![1, 2, 3].includes(sf[0].num)) supported = false
783
+ else {
784
+ const stepFields = nativeFields(sf[0].data)
785
+ if (sf[0].num === 2 && (stepFields.length !== 1 || stepFields[0].num !== 15)) supported = false
786
+ }
787
+ }
788
+ } else if (![3, 4, 5, 6].includes(a.num)) supported = false
789
+ }
790
+ }
791
+ this.checkpoint.missing = missing.size
792
+ this.checkpoint.status = !supported ? "unsupported" : missing.size ? "incomplete" : "complete"
793
+ this.checkpoint.terminal = this.terminal
794
+ }
795
+ terminalSeen(fields) {
796
+ if (this.segment.calls.length) invalid("Cursor ended a turn with unresolved native tool calls", 502)
797
+ this.terminal = true
798
+ this.state = "finalizing"
799
+ this.usageFields = fields
800
+ if (this.checkpoint) this.checkpoint.terminal = true
801
+ clearTimeout(this.batchTimer)
802
+ this.drainTimer = later(() => {
803
+ Promise.resolve().then(() => this.complete()).catch((e) => this.fail(failureOf(e)))
804
+ }, this.limits.drain)
805
+ }
806
+ complete() {
807
+ if (this.completionTask) return this.completionTask
808
+ if (this.error || this.state === "complete") return
809
+ if (!this.terminal) invalid("native Run ended before TurnEnded or a complete final answer", 502)
810
+ const { usageOf } = this.wire
811
+ const measuredInput = this.usageFields?.some((f) => [1, 3, 4].includes(f.num))
812
+ const measuredOutput = this.usageFields?.some((f) => f.num === 2)
813
+ const u = usageOf(this.usageFields ?? [])
814
+ if (!measuredInput) u.input = this.estimate
815
+ if (!measuredOutput) u.output = Math.floor((this.said + 3) / 4)
816
+ // A turn of several model calls: TurnEndedUpdate counts them all, but a
817
+ // client reads the last response's prompt as how full its context is
818
+ // (Codex compacted a 61K context at 1.1M, #156). The last call keeps its
819
+ // own share, the larger of its prompt estimate and the turn's mean per
820
+ // call; the rest is billed as magpie_deferred.
821
+ let earlier = null
822
+ if (this.steps > 1) {
823
+ const whole = u.input + u.cacheRead + u.cacheWrite
824
+ const share = (total, own) => total > 0 ? Math.min(1, Math.max(own, total / this.steps) / total) : 0
825
+ const fi = share(whole, measuredInput ? this.stepEstimate ?? 0 : whole)
826
+ const fo = share(u.output, Math.floor((this.said - this.stepSaid + 3) / 4))
827
+ const own = {
828
+ input: Math.round(u.input * fi), cacheRead: Math.round(u.cacheRead * fi), cacheWrite: Math.round(u.cacheWrite * fi),
829
+ output: Math.round(u.output * fo), reasoning: Math.round(u.reasoning * fo),
830
+ }
831
+ earlier = { input: u.input - own.input, cacheRead: u.cacheRead - own.cacheRead, cacheWrite: u.cacheWrite - own.cacheWrite, output: u.output - own.output }
832
+ Object.assign(u, own)
833
+ }
834
+ const prompt = u.input + u.cacheRead + u.cacheWrite
835
+ this.finalUsage = {
836
+ prompt_tokens: prompt, completion_tokens: u.output, total_tokens: prompt + u.output,
837
+ prompt_tokens_details: { cached_tokens: u.cacheRead, cache_write_tokens: u.cacheWrite },
838
+ ...(this.usageFields?.some((f) => f.num === 5) ? { completion_tokens_details: { reasoning_tokens: u.reasoning } } : {}),
839
+ ...(!measuredInput || !measuredOutput ? { magpie_native: { accounting: "estimated" } } : {}),
840
+ }
841
+ this.state = "finalizing"
842
+ this.closeTransport()
843
+ const finish = (settled) => {
844
+ if (this.error) return
845
+ const more = earlier && settled ? Object.fromEntries(Object.keys(earlier).map((k) => [k, earlier[k] + settled[k]])) : earlier ?? settled
846
+ const deferred = more && more.input + more.output + more.cacheRead + more.cacheWrite > 0
847
+ this.segment.finish({ stop: "stop", usage: {
848
+ ...this.finalUsage,
849
+ ...(deferred ? { magpie_deferred: {
850
+ prompt_tokens: more.input + more.cacheRead + more.cacheWrite,
851
+ completion_tokens: more.output,
852
+ cached_tokens: more.cacheRead,
853
+ cache_write_tokens: more.cacheWrite,
854
+ } } : {}),
855
+ } })
856
+ this.state = "complete"
857
+ this.pool.release(this)
858
+ this.replayTimer = later(() => this.pool.forget(this), this.limits.replayWait)
859
+ }
860
+ if (!this.accounting) return finish(null)
861
+ this.completionTask = this.accounting.settle().then(finish)
862
+ return this.completionTask
863
+ }
864
+ async pump(stream) {
865
+ const { pb, exec, failure } = this.wire
866
+ try {
867
+ for await (const f of stream) {
868
+ if (this.error || this.state === "complete") return
869
+ if (f.end) {
870
+ const e = failure(200, f.data)
871
+ if (e.status < 200 || e.status > 299) throw new NativeSessionError(e.status, e.message)
872
+ if (this.segment.calls.length && this.segment.expected == null) { this.missingCount(); return }
873
+ if (!this.terminal && !this.segment.calls.length && this.segment.content) this.terminalSeen([])
874
+ await this.complete()
875
+ return
876
+ }
877
+ for (const m of nativeFields(f.data)) {
878
+ switch (m.num) {
879
+ case 1:
880
+ for (const u of nativeFields(m.data)) {
881
+ const uf = nativeFields(u.data)
882
+ if (u.num === 1 || u.num === 4) {
883
+ const text = str(uf, 1)
884
+ if (this.terminal || this.state === "awaiting-results") invalid("native output arrived outside a running Chat segment", 502)
885
+ if (text) {
886
+ this.said += text.length
887
+ if (u.num === 1) this.wrote += text.length
888
+ this.segment.emit(u.num === 1 ? { text } : { reasoning: text })
889
+ if (this.batchTimer) this.waitForBatch()
890
+ }
891
+ } else if (u.num === 14) {
892
+ if (!this.segment.content && !this.segment.calls.length) invalid("an empty reply (Cursor ended the turn without text or a tool call)", 502)
893
+ this.terminalSeen(uf)
894
+ } else if (u.num === 27) {
895
+ this.listed(num(uf, 1))
896
+ if (this.error) return
897
+ }
898
+ }
899
+ break
900
+ case 2: {
901
+ const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id), null, true)
902
+ if (c) this.acceptCall(c)
903
+ // request_context is Cursor asking for the environment, not a call
904
+ else if (!nativeFields(m.data).some((e) => e.num === 10)) this.answeredCall()
905
+ break
906
+ }
907
+ case 3:
908
+ this.checkpointReceived(m.data)
909
+ break
910
+ case 4: {
911
+ const kv = nativeFields(m.data)
912
+ const id = num(kv, 1)
913
+ for (const k of kv) {
914
+ if (k.num === 2) {
915
+ const want = field(nativeFields(k.data), 1)?.data.toString("hex") ?? ""
916
+ const b = this.blobs.get(want)
917
+ const res = b ? pb().bytes(1, b) : pb().bytes(2, pb().str(1, "blob not found"))
918
+ await this.reply(pb().bytes(3, pb().varint(1, id).bytes(2, res)).done())
919
+ } else if (k.num === 3) {
920
+ try {
921
+ const set = nativeFields(k.data)
922
+ this.store(field(set, 1)?.data ?? Buffer.alloc(0), field(set, 2)?.data ?? Buffer.alloc(0))
923
+ } catch (e) {
924
+ this.send(pb().bytes(3, pb().varint(1, id).bytes(3, pb().bytes(1, pb().str(1, "native blob could not be retained")))).done())
925
+ throw e
926
+ }
927
+ await this.reply(pb().bytes(3, pb().varint(1, id).bytes(3, Buffer.alloc(0))).done())
928
+ }
929
+ }
930
+ break
931
+ }
932
+ case 5:
933
+ for (const c of nativeFields(m.data)) if (c.num === 1) {
934
+ const id = num(nativeFields(c.data), 1)
935
+ const pending = this.execs.get(id)
936
+ if (pending && !pending.submitted) invalid("Cursor cancelled a pending native tool exec; late results cannot be submitted", 410)
937
+ }
938
+ break
939
+ case 7:
940
+ invalid("unsupported native interaction query", 502)
941
+ }
942
+ }
943
+ }
944
+ if (!this.error && this.state !== "complete") {
945
+ if (this.terminal) await this.complete()
946
+ else invalid("native reply broke off before completing its turn or tool batch: EOF", 502)
947
+ }
948
+ } catch (e) {
949
+ if (!this.error && this.state !== "complete") this.fail(failureOf(e))
950
+ }
951
+ }
952
+ }
953
+
954
+ export const nativeSessions = new NativeSessionPool()
955
+
956
+ export async function clearNativeSessions() {
957
+ await nativeSessions.clear()
958
+ }