@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.
package/src/run.ts ADDED
@@ -0,0 +1,1268 @@
1
+ /**
2
+ * One Cursor AgentService/Run: open an HTTP/2 stream, read it, then tear it down.
3
+ *
4
+ * Ported from magpie's Cursor provider (MIT):
5
+ * https://github.com/magpie-community/plugins/tree/main/packages/cursor
6
+ * which itself was ported from magpie's Go client (internal/provider/cursor*.go).
7
+ *
8
+ * Not ported: parked HTTP/2 sessions, checkpoint resume, run journals, and the
9
+ * OpenCode chat-completions adapter.
10
+ * The deferred dashboard usage ledger is ported: a tool step without TurnEnded
11
+ * reads GetFilteredUsageEvents, owes late events to the conversation, and
12
+ * reports earlier steps as magpie_deferred so prompt_tokens stay this step's.
13
+ * The stateless path still ends the Run when tools are returned. Pi executes
14
+ * them and the next request carries the results as history.
15
+ * The native path keeps that HTTP/2 (or H1/SSE) Run open. A later turn whose
16
+ * tool results use matching call_cursor_<hex>_<seg>_<i> ids writes those
17
+ * results back to it.
18
+ */
19
+ // @ts-nocheck
20
+ import { createHash, randomBytes, randomUUID } from "node:crypto"
21
+ import http2 from "node:http2"
22
+ import { Duplex } from "node:stream"
23
+ import { isDeepStrictEqual } from "node:util"
24
+ import { EMPTY, failure, field, fields, frame, frames, pb, pbAny, pbNum, pbStr, pbValue, regional } from "./codec.ts"
25
+ import { AGENT, API, CALL, GOOS, NAMESPACE, clientVersion, tempDir, unary } from "./client.ts"
26
+ import { canRead, ledger, owe, STEP_WAIT, usageKey } from "./ledger.ts"
27
+ import { request as resolveModel, usable } from "./models.ts"
28
+ import { NATIVE_LIMITS, NativeSessionError, nativeFields, nativeMcpArgs, nativeSessions } from "./native-session.ts"
29
+
30
+ const NO_RESULT = "Tool use was interrupted and did not produce a result."
31
+
32
+ function defaultConnect(origin) {
33
+ return http2.connect(origin)
34
+ }
35
+
36
+ const textOf = (c) =>
37
+ typeof c === "string" ? c : Array.isArray(c) ? c.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("") : ""
38
+
39
+ // joinSplitCalls joins an assistant message onto the assistant message
40
+ // before it when that one made tool calls: Anthropic takes consecutive
41
+ // assistant messages as one turn, and an agent can send a turn's parallel
42
+ // calls split over two of them, answered together after (yetone/magpie#1275).
43
+ // Answered at the second message, the first calls would be marked
44
+ // interrupted and their real results dropped. msgs is left as it is.
45
+ function joinSplitCalls(msgs) {
46
+ const out = []
47
+ for (const m of msgs) {
48
+ const prev = out.at(-1)
49
+ if (m?.role === "assistant" && prev?.role === "assistant" && prev.tool_calls?.length) {
50
+ const content = [textOf(prev.content), textOf(m.content)].filter(Boolean).join("\n\n")
51
+ out[out.length - 1] = { ...prev, content, tool_calls: [...prev.tool_calls, ...(m.tool_calls ?? [])] }
52
+ continue
53
+ }
54
+ out.push(m)
55
+ }
56
+ return out
57
+ }
58
+
59
+ function parseArgs(s) {
60
+ if (s && typeof s === "object") return s
61
+ try {
62
+ const v = JSON.parse(s || "{}")
63
+ return v && typeof v === "object" ? v : {}
64
+ } catch {
65
+ return {}
66
+ }
67
+ }
68
+
69
+ // tools are the caller's tools the model may call.
70
+ function toolsOf(chat) {
71
+ return (chat.tools ?? [])
72
+ .filter((t) => t?.type === "function" && t.function?.name)
73
+ .map((t) => {
74
+ const schema = t.function.parameters ?? { type: "object", properties: {} }
75
+ return { name: t.function.name, description: t.function.description ?? "", schema, schemaText: JSON.stringify(schema) }
76
+ })
77
+ }
78
+
79
+ // catalog lists the caller's tools for the model. It sees MCP tools only
80
+ // through Cursor's GetDynamicTools and CallDynamicTool, and Cursor names
81
+ // them in a prompt of its own, which this conversation goes without:
82
+ // without the list the model says it has no such tool. Each entry is
83
+ // written as the CallDynamicTool call itself: listed as <tool name=...>,
84
+ // some models (GLM-5.3) called the names bare, as tools of their own, and
85
+ // those calls went nowhere (#11).
86
+ function catalog(tools) {
87
+ if (!tools.length) return ""
88
+ let s = `\n\n<dynamic_tool_catalog>\nThe MCP namespace "pi" has the tools below. They are reached only through \`${CALL}\`, never as tools of their own. Each entry is the exact call to make; its arguments must match the schema given. The schemas are complete, so there is no need to call \`GetDynamicTools\` first.\n`
89
+ for (const t of tools) s += `<call>${CALL}({"namespace":"${NAMESPACE}","toolName":"${t.name}","arguments":{...}})\n${t.description}\narguments schema: ${t.schemaText}\n</call>\n`
90
+ return s + "</dynamic_tool_catalog>"
91
+ }
92
+
93
+ // callID is a call's id as Cursor gave it, before the line in it was sent
94
+ // to the caller as __.
95
+ const callID = (id) => (id.startsWith("call_") ? id.replace("__fc_", "\nfc_") : id)
96
+
97
+ function result(id, text, isError) {
98
+ let res = text
99
+ try {
100
+ res = JSON.parse(text)
101
+ } catch {}
102
+ return {
103
+ type: "tool-result",
104
+ toolCallId: callID(id),
105
+ toolName: CALL,
106
+ result: res,
107
+ experimental_content: [{ type: "text", text }],
108
+ ...(isError ? { isError: true } : {}),
109
+ }
110
+ }
111
+
112
+ // messages is the conversation as AI SDK messages, in JSON: the system
113
+ // prompt with the caller's tools listed, then each turn. A tool result
114
+ // answers a call of the reply before it; a call left unanswered is
115
+ // answered for, as the API wants every call to have its result. With it,
116
+ // the user's last words.
117
+ export function conversation(chat, tools) {
118
+ const out = []
119
+ let size = 0
120
+ const add = (m) => out.push(Buffer.from(JSON.stringify(m)))
121
+ const system = []
122
+ let last = "."
123
+ for (const m of chat.messages ?? [])
124
+ if (m.role === "system" || m.role === "developer") system.push(textOf(m.content))
125
+ const sys = system.filter(Boolean).join("\n\n") + catalog(tools)
126
+ size += sys.length
127
+ if (sys) add({ role: "system", content: sys })
128
+ let pending = []
129
+ let results = []
130
+ const answer = () => {
131
+ for (const id of pending) results.push(result(id, NO_RESULT, true))
132
+ pending = []
133
+ if (results.length) add({ role: "tool", content: results })
134
+ results = []
135
+ }
136
+ for (const m of joinSplitCalls(chat.messages ?? [])) {
137
+ if (m.role === "system" || m.role === "developer") continue
138
+ if (m.role === "tool") {
139
+ const id = m.tool_call_id ?? ""
140
+ const i = pending.indexOf(id)
141
+ if (i >= 0) {
142
+ pending.splice(i, 1)
143
+ const text = textOf(m.content)
144
+ size += text.length
145
+ // told Cursor isError (magpie #; Pi sets isError on toolResult)
146
+ results.push(result(id, text, m.is_error === true || m.isError === true))
147
+ }
148
+ continue
149
+ }
150
+ if (m.role === "assistant") {
151
+ answer()
152
+ const content = []
153
+ const text = textOf(m.content)
154
+ if (text) content.push({ type: "text", text })
155
+ size += text.length
156
+ for (const c of m.tool_calls ?? []) {
157
+ if (c?.type && c.type !== "function") continue
158
+ const args = parseArgs(c.function?.arguments)
159
+ size += (c.function?.arguments ?? "").length + (c.function?.name ?? "").length
160
+ content.push({ type: "tool-call", toolCallId: callID(c.id), toolName: CALL, args: { namespace: NAMESPACE, toolName: c.function?.name, arguments: args } })
161
+ pending.push(c.id)
162
+ }
163
+ if (content.length) add({ role: "assistant", content })
164
+ continue
165
+ }
166
+ // the user's
167
+ const content = []
168
+ const parts = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content ?? []
169
+ let first = ""
170
+ for (const p of parts) {
171
+ if (p?.type === "text" && p.text) {
172
+ content.push({ type: "text", text: p.text })
173
+ size += p.text.length
174
+ first ||= p.text
175
+ } else if (p?.type === "image_url") {
176
+ const u = typeof p.image_url === "string" ? p.image_url : p.image_url?.url ?? ""
177
+ const d = /^data:([^;,]+);base64,(.*)$/s.exec(u)
178
+ if (d) content.push({ type: "image", mimeType: d[1], image: { __type: "Uint8Array", hex: Buffer.from(d[2], "base64").toString("hex") } })
179
+ else content.push({ type: "text", text: `[attachment image: ${u}]` })
180
+ } else if (p?.type === "file") {
181
+ content.push({ type: "text", text: `[attachment ${p.file?.filename ?? "file"}]` })
182
+ }
183
+ }
184
+ answer()
185
+ if (first) last = first
186
+ if (content.length) add({ role: "user", content })
187
+ }
188
+ answer()
189
+ for (const t of tools) size += t.name.length + t.description.length + t.schemaText.length
190
+ return { msgs: out, last, estimate: Math.floor(size / 4) }
191
+ }
192
+
193
+ // ---- the request ---------------------------------------------------------------------
194
+
195
+ // toolDef is an McpToolDefinition.
196
+ function toolDef(t) {
197
+ const d = pb().str(1, t.name)
198
+ if (t.description) d.str(2, t.description)
199
+ d.bytes(3, pbValue(t.schema))
200
+ return d.str(4, NAMESPACE).str(5, t.name).str(6, t.schemaText).done()
201
+ }
202
+
203
+ const env = () => pb().str(1, GOOS).str(2, tempDir()).str(10, "UTC")
204
+
205
+ function sessionOf(input) {
206
+ return String(input?.sessionID ?? "").trim().slice(0, 128)
207
+ }
208
+
209
+ // uuidOf is a version 4 UUID made of a hash's first 16 bytes.
210
+ function uuidOf(b) {
211
+ b = Buffer.from(b.subarray(0, 16))
212
+ b[6] = (b[6] & 0x0f) | 0x40
213
+ b[8] = (b[8] & 0x3f) | 0x80
214
+ const h = b.toString("hex")
215
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`
216
+ }
217
+
218
+ // conversationID is stable for one Pi session plus its first user message,
219
+ // so Cursor keeps sending the conversation to the machine that cached the
220
+ // prompt. The first message keeps subagents that share a session id apart.
221
+ // With no session it is "", and each Run gets a new id.
222
+ export function conversationID(chat, session) {
223
+ const key = String(session ?? "").trim()
224
+ if (!key) return ""
225
+ const msgs = Array.isArray(chat?.messages) ? chat.messages : []
226
+ const first = msgs.find((m) => m?.role === "user") ?? msgs[0]
227
+ // role and content only: a timestamp on the same first message must not move the id
228
+ const stable = first === undefined ? "" : JSON.stringify({ role: first.role, content: first.content })
229
+ const sum = createHash("sha256")
230
+ .update("cursor conversation\0" + key + "\0" + stable)
231
+ .digest()
232
+ return uuidOf(sum)
233
+ }
234
+
235
+ // usageOf is a TurnEndedUpdate as magpie counts usage, as the built-in's
236
+ // cursorUsage has it (magpie #498). Its input_tokens is the whole prompt,
237
+ // what was read from the cache and written to it included, as Cursor's
238
+ // own client has it (it takes both out to get the prompt's uncached
239
+ // rest); input is that rest, the cache added back for prompt_tokens. Its
240
+ // reasoning_tokens is kept as reasoning.
241
+ export function usageOf(uf) {
242
+ const [inp, cr, cw] = [pbNum(uf, 1), pbNum(uf, 3), pbNum(uf, 4)]
243
+ return { input: Math.max(inp - cr - cw, 0), output: pbNum(uf, 2), cacheRead: cr, cacheWrite: cw, reasoning: pbNum(uf, 5) }
244
+ }
245
+
246
+ function buildRun(msgs, lastUser, tools, model, conv = "", { maxMode = false, params = [] } = {}) {
247
+ const blobs = new Map()
248
+ const put = (b) => {
249
+ const id = createHash("sha256").update(b).digest()
250
+ blobs.set(id.toString("hex"), b)
251
+ return id
252
+ }
253
+ const state = pb()
254
+ for (const m of msgs) state.bytes(1, put(m))
255
+ const mid = randomUUID()
256
+ const user = pb().str(1, lastUser).str(2, mid).varint(4, 1).done() // mode: agent
257
+ const turn = pb().bytes(1, pb().bytes(1, put(user)).str(10, mid)).done()
258
+ state.bytes(8, put(turn)).varint(10, 1).str(22, "cli")
259
+ const defs = tools.map(toolDef)
260
+ const rc = pb().bytes(4, env())
261
+ const mcp = pb()
262
+ for (const d of defs) {
263
+ rc.bytes(7, d)
264
+ mcp.bytes(1, d)
265
+ }
266
+ const action = pb().bytes(2, pb().bytes(2, rc)) // resume_action
267
+ // ModelDetails: model_id, display_model_id, display_name, max_mode (7);
268
+ // RequestedModel: model_id, max_mode (2), parameters (3)
269
+ const details = pb().str(1, model).str(3, model).str(4, model)
270
+ const requested = pb().str(1, model)
271
+ if (maxMode) {
272
+ details.varint(7, 1)
273
+ requested.varint(2, 1)
274
+ }
275
+ for (const p of params) requested.bytes(3, pb().str(1, p.id).str(2, p.value))
276
+ const rr = pb()
277
+ .bytes(1, state)
278
+ .bytes(2, action)
279
+ .bytes(3, details)
280
+ .bytes(4, mcp)
281
+ .str(5, conv || randomUUID())
282
+ .bytes(9, requested)
283
+ .varint(19, 1) // inline images
284
+ return { first: pb().bytes(1, rr).done(), blobs }
285
+ }
286
+
287
+ // ---- the agent API ---------------------------------------------------------------------
288
+
289
+ // endpoints are the agent API picked for each token (by its hash). As
290
+ // cursor-agent does, it is what ServerConfigService/GetServerConfig names —
291
+ // a team may be served in one region only, and the global API turns it
292
+ // away — asked once a token, and again when fresh is set; the global one
293
+ // while it can't be had.
294
+
295
+ const endpoints = new Map()
296
+ export async function agentURL(tok, fresh) {
297
+ const key = createHash("sha256").update(tok).digest("hex")
298
+ const had = endpoints.get(key)
299
+ if (!fresh && had && (had.listed || Date.now() - had.at < 60_000)) return had.url
300
+ let url = AGENT
301
+ let listed = false
302
+ try {
303
+ const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000)
304
+ for (const raw of [cfg?.agentUrlConfig?.agentUrl, cfg?.agentUrlConfig?.agentnUrl]) {
305
+ try {
306
+ const u = new URL(raw)
307
+ if ((u.protocol === "https:" || u.protocol === "http:") && u.host) {
308
+ url = raw.replace(/\/+$/, "")
309
+ listed = true
310
+ break
311
+ }
312
+ } catch {}
313
+ }
314
+ } catch {}
315
+ // A refresh that learns nothing must not replace a regional URL with the global one.
316
+ if (!listed && fresh && had?.url) return had.url
317
+ endpoints.set(key, { url, at: Date.now(), listed })
318
+ return url
319
+ }
320
+
321
+ export function clearAgentCache() {
322
+ endpoints.clear()
323
+ }
324
+
325
+ // open starts a Run at base: the session, the stream, and the response's
326
+ // status, or an error the request never got past. A Run HTTP/2 can't open
327
+ // goes over HTTP/1.1 (openH1). When the failure says HTTP/2 itself can't be
328
+ // had here (h2Blocked), the Runs after it go straight to HTTP/1.1 for
329
+ // H2.retryAfter, or until a region error sends one back (runAnswer); a
330
+ // connection that failed (refused, no network) or a stream the server
331
+ // refused leaves the next Run to try HTTP/2 again.
332
+ //
333
+ // Tests may inject `connect`; that path stays HTTP/2-only with headerWaitMs.
334
+ let h1Until = 0
335
+ const HEADER_WAIT_MS = 30_000
336
+ const H2 = {
337
+ wait: 15_000,
338
+ retryAfter: 10 * 60_000,
339
+ }
340
+ const H1 = { appendWait: 60_000 }
341
+ // After at least one tool call, a stream that never closes must not pin the turn.
342
+ const TOOL_IDLE_MS = 3_000
343
+ const NET = ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "ECONNRESET", "ETIMEDOUT", "ECONNABORTED", "EPIPE"]
344
+ const cancelledOpen = () => ({ error: { status: 410, message: "the request was cancelled" }, h2Failed: false })
345
+
346
+ function h2Blocked(e) {
347
+ if (e?.h2Timeout) return true
348
+ const code = String(e?.code ?? "")
349
+ const text = `${code} ${e?.message ?? ""}`
350
+ if (NET.some((c) => text.includes(c))) return false
351
+ if (code === "ERR_HTTP2_STREAM_ERROR") return false
352
+ return code.startsWith("ERR_HTTP2") || /h2 is not supported|alpn|nghttp2|protocol error/i.test(text)
353
+ }
354
+
355
+ function connectCode(status) {
356
+ return { 400: "invalid_argument", 401: "unauthenticated", 403: "permission_denied", 429: "resource_exhausted" }[status] ?? "unavailable"
357
+ }
358
+
359
+ function openH2(base, headers, signal, connect = defaultConnect, headerWaitMs = H2.wait) {
360
+ if (signal?.aborted) return Promise.resolve(cancelledOpen())
361
+ return new Promise((resolve) => {
362
+ const u = new URL(base)
363
+ let session
364
+ try {
365
+ session = connect(u.origin)
366
+ } catch (e) {
367
+ resolve({ error: { status: 502, message: e?.message ?? String(e) }, h2Failed: true, blocked: h2Blocked(e) })
368
+ return
369
+ }
370
+ let done = false
371
+ let timer
372
+ const fail = (e, h2Failed = true) => {
373
+ if (done) return
374
+ done = true
375
+ clearTimeout(timer)
376
+ signal?.removeEventListener("abort", abort)
377
+ try { session.destroy() } catch {}
378
+ resolve({ error: { status: h2Failed ? 502 : 410, message: e?.message ?? String(e) }, h2Failed, blocked: h2Failed && h2Blocked(e) })
379
+ }
380
+ const abort = () => fail(new Error("the request was cancelled"), false)
381
+ const wait = Number(headerWaitMs)
382
+ timer = setTimeout(
383
+ () => fail(Object.assign(new Error(`no answer over HTTP/2 in ${(Number.isFinite(wait) && wait > 0 ? wait : H2.wait) / 1000}s`), { h2Timeout: true })),
384
+ Number.isFinite(wait) && wait > 0 ? wait : H2.wait,
385
+ )
386
+ const closed = () => fail(Object.assign(new Error("the connection closed"), { code: "ERR_HTTP2_STREAM_ERROR" }))
387
+ session.on("error", fail)
388
+ const req = session.request({
389
+ ":method": "POST",
390
+ ":path": u.pathname.replace(/\/+$/, "") + "/agent.v1.AgentService/Run",
391
+ ...headers,
392
+ })
393
+ req.on("error", fail)
394
+ req.once("close", () => {
395
+ if (!done) fail(Object.assign(new Error(`the HTTP/2 stream closed before its response (code ${req.rstCode ?? "?"})`), { code: "ERR_HTTP2_STREAM_ERROR" }))
396
+ })
397
+ req.once("response", (h) => {
398
+ if (done) return
399
+ done = true
400
+ clearTimeout(timer)
401
+ signal?.removeEventListener("abort", abort)
402
+ const headersOut = {}
403
+ for (const [k, v] of Object.entries(h ?? {})) headersOut[k] = Array.isArray(v) ? v.join(", ") : String(v ?? "")
404
+ resolve({ session, req, status: Number(h[":status"]), headers: headersOut })
405
+ })
406
+ signal?.addEventListener("abort", abort, { once: true })
407
+ if (signal?.aborted) abort()
408
+ })
409
+ }
410
+
411
+ function openH1(headers, signal) {
412
+ if (signal?.aborted) return Promise.resolve(cancelledOpen())
413
+ const ac = new AbortController()
414
+ const id = headers["x-request-id"]
415
+ const h = { ...headers, "accept-encoding": "identity", "x-cursor-streaming": "true" }
416
+ let ended = false
417
+ let seq = 0
418
+ let reader
419
+ const req = new Duplex({
420
+ read() {},
421
+ write(chunk, _enc, cb) {
422
+ const msg = Buffer.from(chunk).subarray(5)
423
+ const n = seq++
424
+ append(msg, n).then(() => cb(), (e) => cb(e))
425
+ },
426
+ })
427
+ const cleanup = () => {
428
+ signal?.removeEventListener("abort", close)
429
+ ac.abort()
430
+ reader?.cancel().catch(() => {})
431
+ }
432
+ const end = (body) => {
433
+ if (ended || req.destroyed) return
434
+ ended = true
435
+ const f = frame(Buffer.from(body))
436
+ f[0] = 2
437
+ req.push(f)
438
+ req.push(null)
439
+ cleanup()
440
+ }
441
+ const failed = async (res) => {
442
+ const text = await res.text().catch(() => "")
443
+ let e
444
+ try { e = JSON.parse(text) } catch {}
445
+ end(JSON.stringify({ error: typeof e?.code === "string" ? e : { code: connectCode(res.status), message: text.trim() || `HTTP ${res.status}` } }))
446
+ }
447
+ const append = async (msg, n) => {
448
+ if (ended || ac.signal.aborted) return
449
+ const body = pb().str(1, msg.toString("hex")).bytes(2, pb().str(1, id).done()).varint(3, n).done()
450
+ const ms = H1.appendWait + Math.ceil(body.length / 65536) * 1000
451
+ const deadline = AbortSignal.timeout(ms)
452
+ try {
453
+ const res = await fetch(API + "/aiserver.v1.BidiService/BidiAppend", {
454
+ method: "POST",
455
+ headers: { ...h, "content-type": "application/proto", "connect-protocol-version": "1" },
456
+ body,
457
+ signal: AbortSignal.any([ac.signal, deadline]),
458
+ })
459
+ if (ended || ac.signal.aborted) { await res.body?.cancel().catch(() => {}); return }
460
+ if (!res.ok) return failed(res)
461
+ await res.arrayBuffer()
462
+ } catch (e) {
463
+ if (ac.signal.aborted) return
464
+ if (deadline.aborted) return end(JSON.stringify({ error: { code: "deadline_exceeded", message: `BidiAppend got no answer in ${Math.round(ms / 1000)}s` } }))
465
+ end(JSON.stringify({ error: { code: "unavailable", message: `BidiAppend: ${e?.message ?? e}` } }))
466
+ }
467
+ }
468
+ const close = () => {
469
+ ended = true
470
+ cleanup()
471
+ req.destroy()
472
+ }
473
+ signal?.addEventListener("abort", close, { once: true })
474
+ if (signal?.aborted) {
475
+ close()
476
+ return Promise.resolve(cancelledOpen())
477
+ }
478
+ ;(async () => {
479
+ try {
480
+ const res = await fetch(API + "/agent.v1.AgentService/RunSSE", {
481
+ method: "POST",
482
+ headers: { ...h, "content-type": "application/connect+proto", "connect-protocol-version": "1" },
483
+ body: frame(pb().str(1, id).done()),
484
+ signal: ac.signal,
485
+ })
486
+ if (ended || ac.signal.aborted) { await res.body?.cancel().catch(() => {}); return }
487
+ if (!res.ok) return failed(res)
488
+ reader = res.body.getReader()
489
+ try {
490
+ while (!ended && !req.destroyed) {
491
+ const { value, done } = await reader.read()
492
+ if (done) break
493
+ if (!ended && !req.destroyed) req.push(Buffer.from(value))
494
+ }
495
+ } finally {
496
+ reader.releaseLock()
497
+ reader = undefined
498
+ }
499
+ if (!ended && !req.destroyed) {
500
+ ended = true
501
+ req.push(null)
502
+ cleanup()
503
+ }
504
+ } catch (e) {
505
+ if (!ac.signal.aborted) end(JSON.stringify({ error: { code: "unavailable", message: `RunSSE: ${e?.message ?? e}` } }))
506
+ }
507
+ })()
508
+ return Promise.resolve(signal?.aborted ? cancelledOpen() : { session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true, headers: {} })
509
+ }
510
+
511
+ async function open(base, headers, signal, connect = defaultConnect, headerWaitMs = HEADER_WAIT_MS) {
512
+ if (signal?.aborted) return cancelledOpen()
513
+ // Injected connect (tests): HTTP/2 only, keep the caller's header wait.
514
+ if (connect !== defaultConnect) {
515
+ return openH2(base, headers, signal, connect, headerWaitMs)
516
+ }
517
+ if (Date.now() >= h1Until) {
518
+ const o = await openH2(base, headers, signal, defaultConnect, H2.wait)
519
+ if (signal?.aborted) {
520
+ try { o.req?.close?.(http2.constants.NGHTTP2_CANCEL) } catch {}
521
+ try { o.session?.destroy?.() } catch {}
522
+ return cancelledOpen()
523
+ }
524
+ if (!o.h2Failed) return o
525
+ if (o.blocked) h1Until = Date.now() + H2.retryAfter
526
+ }
527
+ if (signal?.aborted) return cancelledOpen()
528
+ return openH1(headers, signal)
529
+ }
530
+
531
+ export function resetH1() { h1Until = 0 }
532
+ export function onH1() { return Date.now() < h1Until }
533
+
534
+ // decode follows the server's messages into the answer's pieces until the
535
+ // turn ends, or the model has made its tool calls. stepUsage / owedUsage are
536
+ // the deferred dashboard ledger (magpie): a tool step without TurnEnded reads
537
+ // usage events; earlier debt leaves as magpie_deferred.
538
+ export async function* decode(stream, { send, blobs, tools, estimate = 0, close, stepUsage, owedUsage, toolIdleMs = TOOL_IDLE_MS }) {
539
+ let calls = 0
540
+ let answered = 0
541
+ let ended = false
542
+ let listed = 0
543
+ const stepDone = () => {
544
+ if (!listed || calls + answered < listed) return false
545
+ if (calls > 0) return true
546
+ listed = 0
547
+ answered = 0
548
+ return false
549
+ }
550
+ let said = 0
551
+ let wrote = 0
552
+ let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 }
553
+ let counted = false
554
+ const finish = (more) => {
555
+ if (!counted && !usage.output) usage.output = Math.floor((said + 3) / 4)
556
+ if (!counted && !usage.input && !usage.cacheRead && !usage.cacheWrite) usage.input = estimate
557
+ const prompt = usage.input + usage.cacheRead + usage.cacheWrite
558
+ const deferred = more && more.input + more.output + more.cacheRead + more.cacheWrite > 0
559
+ return {
560
+ stop: calls > 0 ? "tool_calls" : "stop",
561
+ usage: {
562
+ prompt_tokens: prompt,
563
+ completion_tokens: usage.output,
564
+ total_tokens: prompt + usage.output,
565
+ prompt_tokens_details: { cached_tokens: usage.cacheRead, cache_write_tokens: usage.cacheWrite },
566
+ ...(usage.reasoning ? { completion_tokens_details: { reasoning_tokens: usage.reasoning } } : {}),
567
+ ...(deferred
568
+ ? {
569
+ magpie_deferred: {
570
+ prompt_tokens: more.input + more.cacheRead + more.cacheWrite,
571
+ completion_tokens: more.output,
572
+ cached_tokens: more.cacheRead,
573
+ cache_write_tokens: more.cacheWrite,
574
+ },
575
+ }
576
+ : {}),
577
+ },
578
+ }
579
+ }
580
+ const settled = async () => {
581
+ // Stateless path: tools are full, so cancel this Run. Their results ride the next request.
582
+ if (calls > 0 && !ended && stepUsage) {
583
+ close?.()
584
+ const u = await stepUsage().catch(() => null)
585
+ if (u) usage = u
586
+ counted = u === false || !!u
587
+ } else if (calls > 0) {
588
+ close?.()
589
+ }
590
+ return finish(owedUsage ? await owedUsage(calls === 0).catch(() => null) : null)
591
+ }
592
+ const closeExec = (id) => send(pb().bytes(5, pb().bytes(1, pb().varint(1, id))).done())
593
+ async function* asAsync(src) {
594
+ yield* src
595
+ }
596
+ const iter = asAsync(stream)[Symbol.asyncIterator]()
597
+ let idleTimer
598
+ const moreComing = () => calls > 0 && !(listed > 0 && calls + answered >= listed)
599
+ try {
600
+ while (true) {
601
+ const pending = iter.next().then((v) => ({ v }), (e) => ({ e }))
602
+ let got
603
+ if (moreComing()) {
604
+ got = await Promise.race([
605
+ pending,
606
+ new Promise((resolve) => {
607
+ idleTimer = setTimeout(() => resolve({ idle: true }), toolIdleMs)
608
+ }),
609
+ ])
610
+ clearTimeout(idleTimer)
611
+ } else got = await pending
612
+ if (got.idle) {
613
+ yield await settled()
614
+ return
615
+ }
616
+ if (got.e) throw got.e
617
+ if (got.v.done) {
618
+ if (calls > 0) yield await settled()
619
+ else yield { error: { status: 502, message: "the reply broke off: EOF" } }
620
+ return
621
+ }
622
+ const f = got.v.value
623
+ if (f.end) {
624
+ const e = failure(200, f.data)
625
+ if (e.status < 200 || e.status > 299) yield { error: e }
626
+ else if (wrote === 0 && calls === 0) yield { error: { status: 502, message: "an empty reply" } }
627
+ else yield await settled()
628
+ return
629
+ }
630
+ for (const m of fields(f.data)) {
631
+ switch (m.num) {
632
+ case 1: // interaction_update
633
+ for (const u of fields(m.data)) {
634
+ const uf = fields(u.data)
635
+ switch (u.num) {
636
+ case 1: {
637
+ const t = pbStr(uf, 1)
638
+ if (t) {
639
+ wrote += t.length
640
+ said += t.length
641
+ yield { text: t }
642
+ }
643
+ break
644
+ }
645
+ case 4: {
646
+ const t = pbStr(uf, 1)
647
+ if (t) {
648
+ said += t.length
649
+ yield { reasoning: t }
650
+ }
651
+ break
652
+ }
653
+ case 14: // turn ended, with what it used
654
+ usage = usageOf(uf)
655
+ ended = true
656
+ counted = true
657
+ if (calls === 0) {
658
+ yield wrote === 0 ? { error: { status: 502, message: "an empty reply" } } : await settled()
659
+ return
660
+ }
661
+ yield await settled()
662
+ return
663
+ case 27: // how many tool calls the step makes
664
+ listed = pbNum(uf, 1)
665
+ if (stepDone()) {
666
+ yield await settled()
667
+ return
668
+ }
669
+ break
670
+ }
671
+ }
672
+ break
673
+ case 2: {
674
+ const call = exec(m.data, tools, send, closeExec)
675
+ if (call) {
676
+ said += (call.args ?? "").length
677
+ yield { tool: { index: calls++, ...call } }
678
+ } else if (!fields(m.data).some((e) => e.num === 10)) answered++
679
+ if (stepDone()) {
680
+ yield await settled()
681
+ return
682
+ }
683
+ break
684
+ }
685
+ case 4: {
686
+ const kv = fields(m.data)
687
+ const id = pbNum(kv, 1)
688
+ for (const k of kv) {
689
+ if (k.num === 2) {
690
+ const want = field(fields(k.data), 1)?.data.toString("hex") ?? ""
691
+ const b = blobs.get(want)
692
+ const res = b ? pb().bytes(1, b) : pb().bytes(2, pb().str(1, "blob not found"))
693
+ send(pb().bytes(3, pb().varint(1, id).bytes(2, res)).done())
694
+ } else if (k.num === 3) {
695
+ send(pb().bytes(3, pb().varint(1, id).bytes(3, EMPTY)).done())
696
+ }
697
+ }
698
+ break
699
+ }
700
+ }
701
+ }
702
+ }
703
+ } catch (e) {
704
+ if (calls > 0 && /EOF/.test(e?.message ?? "")) {
705
+ yield await settled()
706
+ return
707
+ }
708
+ yield { error: { status: 502, message: "the reply broke off: " + (e?.message ?? e) } }
709
+ } finally {
710
+ clearTimeout(idleTimer)
711
+ }
712
+ }
713
+
714
+ // exec answers what the server asks the client to run: a call of the
715
+ // caller's tools is returned, the list of them is given, and anything else
716
+ // is refused.
717
+ const NAMESPACES = [NAMESPACE]
718
+ const bareName = (s) => {
719
+ for (const ns of NAMESPACES) if (s.startsWith(ns + "-")) return s.slice(ns.length + 1)
720
+ return s
721
+ }
722
+
723
+ function exec(msg, tools, send, closeExec, refused, native = false) {
724
+ const es = native ? nativeFields(msg) : fields(msg)
725
+ if (native && es.some((e) => e.num === 1 && (e.wire !== 0 || !Number.isInteger(e.n) || e.n < 0 || e.n > 0xffffffff)))
726
+ throw new NativeSessionError(502, "invalid native exec request ID")
727
+ const id = pbNum(es, 1)
728
+ const execID = pbStr(es, 15)
729
+ let nativeCall, nativeUnavailable = false
730
+ if (native) for (const e of es) if (e.num === 11) {
731
+ if (e.wire !== 2) throw new NativeSessionError(502, "invalid native MCP argument envelope")
732
+ const { fields: a, args } = nativeMcpArgs(e.data)
733
+ const name = pbStr(a, 5) || bareName(pbStr(a, 1))
734
+ const provider = pbStr(a, 4)
735
+ const server = pbStr(a, 9)
736
+ if (provider && !NAMESPACES.includes(provider) || server && !NAMESPACES.includes(server)) nativeUnavailable = true
737
+ if (pbNum(a, 7) || field(a, 6)) nativeUnavailable = true
738
+ if (!tools.some((t) => t.name === name)) nativeUnavailable = true
739
+ if (!pbStr(a, 5) && !NAMESPACES.some((ns) => pbStr(a, 1) === ns + "-" + name)) nativeUnavailable = true
740
+ const call = { requestID: id, execID, nativeID: pbStr(a, 3), name, args }
741
+ if (nativeCall && !isDeepStrictEqual(nativeCall, call)) throw new NativeSessionError(502, "ambiguous repeated native MCP argument envelopes")
742
+ nativeCall ??= call
743
+ }
744
+ const answer = (num, res) => {
745
+ send(pb().bytes(2, pb().varint(1, id).str(15, execID).bytes(num, res)).done())
746
+ closeExec(id)
747
+ }
748
+ const unavailable = () => {
749
+ const kind = es.find((e) => ![1, 15, 19, 55].includes(e.num))?.num ?? 0
750
+ refused?.set(kind, (refused.get(kind) ?? 0) + 1)
751
+ send(pb().bytes(5, pb().bytes(2, pb().varint(1, id).str(2, "not available"))).done())
752
+ closeExec(id)
753
+ return null
754
+ }
755
+ if (nativeUnavailable) return unavailable()
756
+ for (const e of es) {
757
+ switch (e.num) {
758
+ case 11: {
759
+ // mcp_args: a call of the caller's tools
760
+ if (native) return { ...nativeCall, args: JSON.stringify(nativeCall.args) }
761
+ const a = fields(e.data)
762
+ const args = {}
763
+ for (const kv of a) {
764
+ if (kv.num !== 2) continue
765
+ const ef = fields(kv.data)
766
+ const v = field(ef, 2)
767
+ args[pbStr(ef, 1)] = v ? pbAny(v.data) : null
768
+ }
769
+ const name = pbStr(a, 5) || pbStr(a, 1).replace(/^pi-/, "")
770
+ // an OpenAI model's id is its call's and its item's, a line apart,
771
+ // which no caller would take as an id: the line goes as __
772
+ const cid = pbStr(a, 3).replaceAll("\n", "__") || "call_" + randomBytes(12).toString("hex")
773
+ if (!tools.some((t) => t.name === name)) {
774
+ send(pb().bytes(5, pb().bytes(2, pb().varint(1, id).str(2, "not available"))).done())
775
+ closeExec(id)
776
+ return null
777
+ }
778
+ return { id: cid, name, args: JSON.stringify(args) }
779
+ }
780
+ case 36: {
781
+ // mcp_state_exec_args: the tools there are
782
+ const srv = pb().str(1, NAMESPACE).str(2, NAMESPACE).str(7, "connected")
783
+ for (const t of tools) srv.bytes(5, toolDef(t))
784
+ answer(36, pb().bytes(1, pb().bytes(1, srv)))
785
+ return null
786
+ }
787
+ case 10: // request_context_args
788
+ answer(10, pb().bytes(1, pb().bytes(1, pb().bytes(4, env()))))
789
+ return null
790
+ }
791
+ }
792
+ // a shell, a file read or an edit of Cursor's own: never run
793
+ return unavailable()
794
+ }
795
+
796
+ const maxOnly = new Set()
797
+ const maxRequired = (msg) => /max[ _]mode[ _]required|requires max mode/i.test(String(msg ?? ""))
798
+
799
+ function cursorHeaders(tok, version, extra) {
800
+ const headers = {
801
+ "content-type": "application/connect+proto",
802
+ "connect-protocol-version": "1",
803
+ authorization: `Bearer ${tok}`,
804
+ "x-cursor-client-version": version,
805
+ "x-cursor-client-type": "cli",
806
+ "x-ghost-mode": "true",
807
+ "x-request-id": randomUUID(),
808
+ "x-cursor-agent-allowed-tools": "mcp_tool_call,get_mcp_tools_tool_call",
809
+ }
810
+ for (const [key, value] of Object.entries(extra ?? {})) {
811
+ const same = Object.keys(headers).filter((k) => k.toLowerCase() === key.toLowerCase())
812
+ if (value === null || value === undefined) {
813
+ for (const k of same) delete headers[k]
814
+ continue
815
+ }
816
+ if (same.length === 0) headers[key] = String(value)
817
+ else for (const k of same) headers[k] = String(value)
818
+ }
819
+ return headers
820
+ }
821
+
822
+ async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }) {
823
+ const cid = convID || randomUUID()
824
+ const since = Date.now()
825
+ const book = ledger(tok, cid, since, signal, !!convID)
826
+ let modelId = id
827
+ if (onPayload) {
828
+ const replaced = await onPayload({ model: modelId, maxMode: !!maxMode, params, conversationId: cid, tools: tools.map((t) => t.name) })
829
+ if (replaced && typeof replaced === "object" && !Buffer.isBuffer(replaced) && typeof replaced.model === "string" && replaced.model) {
830
+ modelId = replaced.model
831
+ }
832
+ }
833
+ const { first, blobs } = buildRun(conv.msgs, conv.last, tools, modelId, cid, { maxMode, params })
834
+ const o = await open(base, cursorHeaders(tok, await clientVersion(), headers), signal, connect, headerWaitMs)
835
+ if (o.error) return book.done(), { ...o, h1: !!o.h1 }
836
+ if (onResponse) await onResponse({ status: o.status, headers: o.headers ?? {} })
837
+ const { session, req } = o
838
+ let closed = false
839
+ const send = (msg) => {
840
+ if (!closed && !req.destroyed && req.writable) req.write(frame(msg))
841
+ }
842
+ const heartbeat = setInterval(() => send(pb().bytes(7, EMPTY).done()), 5000)
843
+ heartbeat.unref?.()
844
+ const close = () => {
845
+ if (closed) return
846
+ closed = true
847
+ clearInterval(heartbeat)
848
+ try {
849
+ req.close(http2.constants.NGHTTP2_CANCEL)
850
+ } catch {}
851
+ try {
852
+ session.close()
853
+ } catch {}
854
+ setTimeout(() => {
855
+ try {
856
+ session.destroy()
857
+ } catch {}
858
+ }, 1000).unref?.()
859
+ }
860
+ signal?.addEventListener("abort", close, { once: true })
861
+ if (signal?.aborted) {
862
+ close()
863
+ book.done()
864
+ return cancelledOpen()
865
+ }
866
+ send(first)
867
+ if (o.status < 200 || o.status > 299) {
868
+ const chunks = []
869
+ try {
870
+ for await (const c of req) chunks.push(c)
871
+ } catch {}
872
+ close()
873
+ book.done()
874
+ return { error: failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)), h1: !!o.h1 }
875
+ }
876
+ const it = decode(frames(req), {
877
+ send,
878
+ blobs,
879
+ tools,
880
+ estimate: conv.estimate,
881
+ close,
882
+ stepUsage: book.own,
883
+ owedUsage: book.owed,
884
+ toolIdleMs,
885
+ })
886
+ const wrapped = (async function* () {
887
+ try {
888
+ yield* it
889
+ } finally {
890
+ close()
891
+ book.done()
892
+ }
893
+ })()
894
+ const head = await wrapped.next()
895
+ if (head.done) return book.done(), { error: { status: 502, message: "an empty reply" }, h1: !!o.h1 }
896
+ if (head.value?.error) {
897
+ await wrapped.return?.()
898
+ return { error: head.value.error, h1: !!o.h1 }
899
+ }
900
+ return {
901
+ conversationId: cid,
902
+ h1: !!o.h1,
903
+ events: (async function* () {
904
+ yield head.value
905
+ yield* wrapped
906
+ })(),
907
+ }
908
+ }
909
+
910
+ // withDelivery marks the sealed segment clean once the caller has its stop
911
+ // event. The next turn can then resume. Until then prepare reports the owner busy.
912
+ function withDelivery(owner, events) {
913
+ const it = events[Symbol.asyncIterator]()
914
+ return {
915
+ async next() {
916
+ const r = await it.next()
917
+ if (r.value?.stop) owner.delivered()
918
+ return r
919
+ },
920
+ return: () => it.return?.(),
921
+ [Symbol.asyncIterator]() { return this },
922
+ }
923
+ }
924
+
925
+ // nativeTransport queues writes on one open Run. Heartbeats and exec answers
926
+ // never wait. A KV reply waits until the queue has room.
927
+ function nativeTransport(req, close, fail, limits = NATIVE_LIMITS) {
928
+ const outbound = { bytes: 0, messages: 0 }
929
+ const queue = []
930
+ let closed = false, flushing = false, rejectWrite
931
+ const waiters = new Set()
932
+ const spare = (n) => Math.floor(n / 8)
933
+ const fits = (size) => outbound.messages === 0 || (outbound.messages + 1 + spare(limits.outboundMessages) <= limits.outboundMessages
934
+ && outbound.bytes + size + spare(limits.outboundBytes) <= limits.outboundBytes)
935
+ const wake = () => {
936
+ for (const w of waiters) if (closed || fits(w.size)) w.done()
937
+ }
938
+ const flush = async () => {
939
+ if (closed || flushing) return
940
+ flushing = true
941
+ try {
942
+ while (!closed && queue.length) {
943
+ const packet = queue.shift()
944
+ await new Promise((resolve, reject) => {
945
+ let written = false, drained = false, started = false, settled = false
946
+ const finish = (error) => {
947
+ if (settled) return
948
+ settled = true
949
+ rejectWrite = undefined
950
+ req.removeListener("drain", drain)
951
+ req.removeListener("error", failed)
952
+ req.removeListener("close", lost)
953
+ error ? reject(error) : resolve()
954
+ }
955
+ const check = () => { if (started && written && drained) finish() }
956
+ const drain = () => { drained = true; check() }
957
+ const failed = (e) => finish(e)
958
+ const lost = () => finish(new NativeSessionError(502, "native transport closed during a write; its outcome is uncertain"))
959
+ rejectWrite = finish
960
+ req.once("drain", drain)
961
+ req.once("error", failed)
962
+ req.once("close", lost)
963
+ try {
964
+ drained = req.write(packet, (e) => {
965
+ if (e) return finish(e)
966
+ written = true
967
+ check()
968
+ }) || drained
969
+ started = true
970
+ if (drained) req.removeListener("drain", drain)
971
+ check()
972
+ } catch (e) { finish(e) }
973
+ })
974
+ if (!closed) { outbound.bytes -= packet.length; outbound.messages--; wake() }
975
+ }
976
+ } catch (e) {
977
+ if (!closed) fail(e)
978
+ } finally { flushing = false }
979
+ }
980
+ return {
981
+ outbound,
982
+ send(message) {
983
+ if (closed || req.destroyed || !req.writable) throw new NativeSessionError(502, "native transport is no longer writable")
984
+ const size = message.length + 5
985
+ if (outbound.bytes + size > limits.outboundBytes) throw new NativeSessionError(503, "native outbound bytes limit reached")
986
+ if (outbound.messages + 1 > limits.outboundMessages) throw new NativeSessionError(503, "native outbound messages limit reached")
987
+ outbound.bytes += size
988
+ outbound.messages++
989
+ queue.push(frame(message))
990
+ void flush()
991
+ },
992
+ room(size) {
993
+ if (closed || fits(size)) return Promise.resolve()
994
+ return new Promise((resolve, reject) => {
995
+ const w = {
996
+ size,
997
+ done() {
998
+ waiters.delete(w)
999
+ clearTimeout(w.timer)
1000
+ resolve()
1001
+ },
1002
+ }
1003
+ w.timer = setTimeout(() => {
1004
+ waiters.delete(w)
1005
+ const which = outbound.bytes + size + spare(limits.outboundBytes) > limits.outboundBytes ? "bytes" : "messages"
1006
+ reject(new NativeSessionError(503, `native outbound ${which} limit reached: the queue did not drain for ${Math.round(limits.writeWait / 1000)}s`))
1007
+ }, limits.writeWait)
1008
+ w.timer.unref?.()
1009
+ waiters.add(w)
1010
+ })
1011
+ },
1012
+ close() {
1013
+ if (closed) return
1014
+ closed = true
1015
+ queue.length = 0
1016
+ outbound.bytes = 0
1017
+ outbound.messages = 0
1018
+ wake()
1019
+ rejectWrite?.(new NativeSessionError(410, "native transport was cancelled"))
1020
+ close()
1021
+ },
1022
+ }
1023
+ }
1024
+
1025
+ // runNative keeps the Run open across tool batches. Accounting uses the
1026
+ // deferred dashboard ledger: settle collects earlier debt as magpie_deferred;
1027
+ // an abandoned pending Run is owed once to the same conversation.
1028
+ async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, params, native, connect, onResponse, onPayload, headers, headerWaitMs }) {
1029
+ const cid = convID || randomUUID()
1030
+ const since = Date.now()
1031
+ const accounting = new AbortController()
1032
+ const book = ledger(tok, cid, since, accounting.signal, !!convID, { before: since })
1033
+ const debtKey = usageKey(tok, cid)
1034
+ let started = false, settled = false, deferred = null
1035
+ native.accounting = {
1036
+ started() { started = true },
1037
+ async settle() {
1038
+ const more = await book.owed(true)
1039
+ if (settled) {
1040
+ if (more) owe(debtKey, { carry: more })
1041
+ return null
1042
+ }
1043
+ deferred = more
1044
+ return more
1045
+ },
1046
+ delivered() {
1047
+ if (settled) return
1048
+ settled = true
1049
+ deferred = null
1050
+ book.done()
1051
+ accounting.abort()
1052
+ },
1053
+ abandon() {
1054
+ if (settled) return
1055
+ settled = true
1056
+ book.done()
1057
+ accounting.abort()
1058
+ if (deferred) owe(debtKey, { carry: deferred })
1059
+ deferred = null
1060
+ if (started && native.segments > 0 && !native.finalUsage && convID && canRead(tok)) {
1061
+ owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt })
1062
+ }
1063
+ },
1064
+ }
1065
+ let modelId = id
1066
+ if (onPayload) {
1067
+ const replaced = await onPayload({ model: modelId, maxMode: !!maxMode, params, conversationId: cid, tools: tools.map((t) => t.name) })
1068
+ if (replaced && typeof replaced === "object" && !Buffer.isBuffer(replaced) && typeof replaced.model === "string" && replaced.model) {
1069
+ modelId = replaced.model
1070
+ }
1071
+ }
1072
+ const { first, blobs } = buildRun(conv.msgs, conv.last, tools, modelId, cid, { maxMode, params })
1073
+ native.chatTools = tools
1074
+ native.attach(signal)
1075
+ if (native.error) {
1076
+ nativeSessions.forget(native)
1077
+ return { error: native.error }
1078
+ }
1079
+ const o = await open(base, cursorHeaders(tok, await clientVersion(), headers), native.ac.signal, connect, headerWaitMs)
1080
+ if (o.error) {
1081
+ native.fail(o.error)
1082
+ nativeSessions.forget(native)
1083
+ return { ...o, h1: !!o.h1 }
1084
+ }
1085
+ if (onResponse) await onResponse({ status: o.status, headers: o.headers ?? {} })
1086
+ const { session, req } = o
1087
+ const close = () => {
1088
+ try { req.close(http2.constants.NGHTTP2_CANCEL) } catch {}
1089
+ try { session.close() } catch {}
1090
+ try { session.destroy() } catch {}
1091
+ }
1092
+ const transport = nativeTransport(req, close, (e) => native.fail({ status: e.status ?? 502, message: e.message }), native.limits)
1093
+ try {
1094
+ native.bind(transport, blobs, conv.estimate)
1095
+ if (native.error) {
1096
+ nativeSessions.forget(native)
1097
+ return { error: native.error, h1: !!o.h1 }
1098
+ }
1099
+ native.send(first)
1100
+ native.accounting.started()
1101
+ if (o.status < 200 || o.status > 299) {
1102
+ const chunks = []
1103
+ for await (const c of req) chunks.push(c)
1104
+ native.fail(failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)))
1105
+ nativeSessions.forget(native)
1106
+ return { error: native.error, h1: !!o.h1 }
1107
+ }
1108
+ native.pumpTask = (async () => {
1109
+ await native.pump(frames(req))
1110
+ })()
1111
+ const response = native.response()
1112
+ const it = response.events
1113
+ const head = await it.next()
1114
+ if (head.done || head.value.error) {
1115
+ const error = head.value?.error ?? { status: 502, message: "an empty reply" }
1116
+ await native.cancel(error.message)
1117
+ nativeSessions.forget(native)
1118
+ return { error, h1: !!o.h1 }
1119
+ }
1120
+ let firstEvent = head
1121
+ const events = {
1122
+ next() {
1123
+ if (firstEvent) {
1124
+ const r = firstEvent
1125
+ firstEvent = null
1126
+ if (r.value?.stop) native.delivered()
1127
+ return Promise.resolve(r)
1128
+ }
1129
+ return it.next().then((r) => {
1130
+ if (r.value?.stop) native.delivered()
1131
+ return r
1132
+ })
1133
+ },
1134
+ return: () => it.return(),
1135
+ [Symbol.asyncIterator]() { return this },
1136
+ }
1137
+ return { conversationId: cid, events, h1: !!o.h1 }
1138
+ } catch (e) {
1139
+ native.fail({ status: e.status ?? 502, message: e.message })
1140
+ await native.pumpTask
1141
+ nativeSessions.forget(native)
1142
+ return { error: native.error, h1: !!o.h1 }
1143
+ }
1144
+ }
1145
+
1146
+ export function clearMaxOnly() {
1147
+ maxOnly.clear()
1148
+ }
1149
+
1150
+ export { nativeSessions } from "./native-session.ts"
1151
+ export { STEP_WAIT, ledger, owed, misses, unreadable, clearLedger, usageKey } from "./ledger.ts"
1152
+
1153
+ /** One user-visible turn. A regional miss retries once, and only when the agent URL changed. */
1154
+ export async function runAnswer({
1155
+ tok,
1156
+ model,
1157
+ effort = "",
1158
+ fast,
1159
+ messages,
1160
+ tools = [],
1161
+ session = "",
1162
+ signal,
1163
+ connect,
1164
+ resolveAgentURL = agentURL,
1165
+ rawModels,
1166
+ onResponse,
1167
+ onPayload,
1168
+ headers,
1169
+ headerWaitMs = HEADER_WAIT_MS,
1170
+ toolIdleMs = TOOL_IDLE_MS,
1171
+ }: {
1172
+ tok: string
1173
+ model?: string
1174
+ effort?: string
1175
+ fast?: boolean
1176
+ messages?: unknown[]
1177
+ tools?: { name: string; description?: string; schema?: unknown }[]
1178
+ session?: string
1179
+ signal?: AbortSignal
1180
+ connect?: (origin: string) => unknown
1181
+ resolveAgentURL?: (tok: string, fresh: boolean) => Promise<string> | string
1182
+ rawModels?: unknown
1183
+ onResponse?: (response: { status: number; headers: Record<string, string> }) => unknown
1184
+ onPayload?: (payload: unknown) => unknown
1185
+ headers?: Record<string, string | null | undefined>
1186
+ headerWaitMs?: number
1187
+ toolIdleMs?: number
1188
+ }): Promise<{
1189
+ error?: { status?: number; message?: string }
1190
+ conversationId?: string
1191
+ events?: AsyncIterable<{
1192
+ text?: string
1193
+ reasoning?: string
1194
+ tool?: { id: string; name: string; args: string }
1195
+ stop?: string
1196
+ usage?: {
1197
+ prompt_tokens?: number
1198
+ completion_tokens?: number
1199
+ prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number }
1200
+ completion_tokens_details?: { reasoning_tokens?: number }
1201
+ }
1202
+ error?: { status?: number; message?: string }
1203
+ }>
1204
+ }> {
1205
+ const chat = {
1206
+ model,
1207
+ messages,
1208
+ reasoning_effort: effort,
1209
+ ...(fast === true ? { service_tier: "fast" } : fast === false ? { service_tier: "default" } : {}),
1210
+ tools: tools.map((t) => ({
1211
+ type: "function",
1212
+ function: {
1213
+ name: t.name,
1214
+ description: t.description ?? "",
1215
+ parameters: t.schema ?? { type: "object", properties: {} },
1216
+ },
1217
+ })),
1218
+ }
1219
+ const listed = toolsOf(chat)
1220
+ const convID = conversationID(chat, sessionOf({ sessionID: session }))
1221
+ const prepared = nativeSessions.prepare(tok, chat, convID, listed)
1222
+ if (prepared.owner) {
1223
+ try {
1224
+ const conv = conversation(chat, listed)
1225
+ const resumed = prepared.owner.resume({ ...prepared, estimate: conv.estimate }, signal)
1226
+ return { conversationId: convID, events: withDelivery(prepared.owner, resumed.events) }
1227
+ } catch (e) {
1228
+ return { error: { status: e?.status ?? 502, message: e?.message ?? String(e) } }
1229
+ }
1230
+ }
1231
+ let raw = rawModels
1232
+ if (raw === undefined) {
1233
+ try {
1234
+ raw = await usable(tok)
1235
+ } catch {
1236
+ raw = []
1237
+ }
1238
+ }
1239
+ const resolved = resolveModel(raw, String(model ?? ""), effort, fast)
1240
+ let id = resolved.id
1241
+ let params = resolved.params
1242
+ let maxMode = resolved.maxMode || maxOnly.has(id)
1243
+ const conv = conversation(chat, listed)
1244
+ let base = await resolveAgentURL(tok, false)
1245
+ const once = async () => {
1246
+ const native = prepared.fallback ? null : nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure })
1247
+ const args = { tok, base, id, tools: listed, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }
1248
+ let response = native ? await runNative({ ...args, native }) : await runOnce(args)
1249
+ if (response.error?.retentionIneligible && !signal?.aborted) response = await runOnce(args)
1250
+ return response
1251
+ }
1252
+ let ran = await once()
1253
+ if (ran.error && regional(ran.error.message)) {
1254
+ resetH1()
1255
+ const fresh = await resolveAgentURL(tok, true)
1256
+ const viaH1 = !!ran.h1
1257
+ if (fresh !== base || viaH1) {
1258
+ base = fresh
1259
+ ran = await once()
1260
+ }
1261
+ }
1262
+ if (ran.error && !maxMode && maxRequired(ran.error.message)) {
1263
+ maxMode = true
1264
+ maxOnly.add(id)
1265
+ ran = await once()
1266
+ }
1267
+ return ran
1268
+ }