@caph42/pi-cursor-provider 0.5.0 → 0.5.2

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