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