@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.
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Ported from magpie's Cursor provider (MIT):
3
+ * https://github.com/magpie-community/plugins/tree/main/packages/cursor
4
+ */
5
+ import { randomUUID } from "node:crypto"
6
+ import http2 from "node:http2"
7
+ import { Duplex } from "node:stream"
8
+ import { frame, pb } from "./codec.ts"
9
+ import { API } from "./client.ts"
10
+ import { trace } from "./trace.ts"
11
+
12
+ export type RunStream = Duplex & { close(code?: number): void }
13
+
14
+ export type Opened = {
15
+ error?: undefined
16
+ h2Failed?: undefined
17
+ blocked?: undefined
18
+ session: { close(): void; destroy(): void }
19
+ req: RunStream
20
+ status: number
21
+ headers: Record<string, string>
22
+ /** Set when the Run went over HTTP/1.1 (RunSSE plus BidiAppend). */
23
+ h1?: boolean
24
+ }
25
+
26
+ /** A Run that never got its response headers. h2Failed: HTTP/2 itself failed. blocked: and it will keep failing here. */
27
+ export type OpenFailed = {
28
+ error: { status: number; message: string }
29
+ h2Failed: boolean
30
+ blocked?: boolean
31
+ session?: undefined
32
+ req?: undefined
33
+ h1?: undefined
34
+ }
35
+
36
+ /** Opens an HTTP/2 session to an origin. Tests hand in fakes; those Runs stay on HTTP/2. */
37
+ export type Connect = (origin: string) => unknown
38
+
39
+ export type OpenRequest = {
40
+ base: string
41
+ tok: string
42
+ /** The caller's header overrides. null or undefined removes a header. */
43
+ headers?: Record<string, string | null | undefined>
44
+ signal?: AbortSignal
45
+ connect?: Connect
46
+ headerWaitMs?: number
47
+ version: string
48
+ }
49
+
50
+ export type TransportState = {
51
+ transport: { via: "h2" } | { via: "h1"; until: number }
52
+ }
53
+
54
+ type Thrown = { message?: string; code?: unknown; h2Timeout?: boolean } | null | undefined
55
+
56
+ function defaultConnect(origin: string) {
57
+ return http2.connect(origin)
58
+ }
59
+
60
+ let h1Until = 0
61
+ const H2 = {
62
+ wait: 15_000,
63
+ retryAfter: 10 * 60_000,
64
+ }
65
+ const H1 = { appendWait: 60_000 }
66
+ const NET = ["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH", "ECONNRESET", "ETIMEDOUT", "ECONNABORTED", "EPIPE"]
67
+
68
+ export const cancelledOpen = (): OpenFailed => ({ error: { status: 410, message: "the request was cancelled" }, h2Failed: false })
69
+
70
+ function h2Blocked(e: Thrown): boolean {
71
+ if (e?.h2Timeout) return true
72
+ const code = String(e?.code ?? "")
73
+ const text = `${code} ${e?.message ?? ""}`
74
+ if (NET.some((c) => text.includes(c))) return false
75
+ if (code === "ERR_HTTP2_STREAM_ERROR") return false
76
+ return code.startsWith("ERR_HTTP2") || /h2 is not supported|alpn|nghttp2|protocol error/i.test(text)
77
+ }
78
+
79
+ function connectCode(status: number): string {
80
+ return ({ 400: "invalid_argument", 401: "unauthenticated", 403: "permission_denied", 429: "resource_exhausted" } as Record<number, string>)[status] ?? "unavailable"
81
+ }
82
+
83
+ function cursorHeaders(tok: string, version: string, extra: OpenRequest["headers"]): Record<string, string> {
84
+ const headers: Record<string, string> = {
85
+ "content-type": "application/connect+proto",
86
+ "connect-protocol-version": "1",
87
+ authorization: `Bearer ${tok}`,
88
+ "x-cursor-client-version": version,
89
+ "x-cursor-client-type": "cli",
90
+ "x-ghost-mode": "true",
91
+ "x-request-id": randomUUID(),
92
+ "x-cursor-agent-allowed-tools": "mcp_tool_call,get_mcp_tools_tool_call",
93
+ }
94
+ for (const [key, value] of Object.entries(extra ?? {})) {
95
+ const same = Object.keys(headers).filter((k) => k.toLowerCase() === key.toLowerCase())
96
+ if (value === null || value === undefined) {
97
+ for (const k of same) delete headers[k]
98
+ continue
99
+ }
100
+ if (same.length === 0) headers[key] = String(value)
101
+ else for (const k of same) headers[k] = String(value)
102
+ }
103
+ return headers
104
+ }
105
+
106
+ function openH2(base: string, headers: Record<string, string>, signal: AbortSignal | undefined, connect: Connect, headerWaitMs: number): Promise<Opened | OpenFailed> {
107
+ if (signal?.aborted) return Promise.resolve(cancelledOpen())
108
+ return new Promise((resolve) => {
109
+ const u = new URL(base)
110
+ let session: http2.ClientHttp2Session
111
+ try {
112
+ session = connect(u.origin) as http2.ClientHttp2Session
113
+ } catch (caught) {
114
+ const e = caught as Thrown
115
+ resolve({ error: { status: 502, message: e?.message ?? String(e) }, h2Failed: true, blocked: h2Blocked(e) })
116
+ return
117
+ }
118
+ let done = false
119
+ let timer: ReturnType<typeof setTimeout> | undefined
120
+ const fail = (e: Error & { code?: unknown; h2Timeout?: boolean }, h2Failed = true) => {
121
+ if (done) return
122
+ done = true
123
+ clearTimeout(timer)
124
+ signal?.removeEventListener("abort", abort)
125
+ try { session.destroy() } catch {}
126
+ resolve({ error: { status: h2Failed ? 502 : 410, message: e?.message ?? String(e) }, h2Failed, blocked: h2Failed && h2Blocked(e) })
127
+ }
128
+ const abort = () => fail(new Error("the request was cancelled"), false)
129
+ const wait = Number(headerWaitMs)
130
+ timer = setTimeout(
131
+ () => fail(Object.assign(new Error(`no answer over HTTP/2 in ${(Number.isFinite(wait) && wait > 0 ? wait : H2.wait) / 1000}s`), { h2Timeout: true })),
132
+ Number.isFinite(wait) && wait > 0 ? wait : H2.wait,
133
+ )
134
+ session.on("error", fail)
135
+ const req = session.request({
136
+ ":method": "POST",
137
+ ":path": u.pathname.replace(/\/+$/, "") + "/agent.v1.AgentService/Run",
138
+ ...headers,
139
+ })
140
+ req.on("error", fail)
141
+ req.once("close", () => {
142
+ if (!done) fail(Object.assign(new Error(`the HTTP/2 stream closed before its response (code ${req.rstCode ?? "?"})`), { code: "ERR_HTTP2_STREAM_ERROR" }))
143
+ })
144
+ req.once("response", (h) => {
145
+ if (done) return
146
+ done = true
147
+ clearTimeout(timer)
148
+ signal?.removeEventListener("abort", abort)
149
+ const headersOut: Record<string, string> = {}
150
+ for (const [k, v] of Object.entries(h ?? {})) headersOut[k] = Array.isArray(v) ? v.join(", ") : String(v ?? "")
151
+ resolve({ session, req, status: Number(h[":status"]), headers: headersOut })
152
+ })
153
+ signal?.addEventListener("abort", abort, { once: true })
154
+ if (signal?.aborted) abort()
155
+ })
156
+ }
157
+
158
+ function openH1(headers: Record<string, string>, signal: AbortSignal | undefined): Promise<Opened | OpenFailed> {
159
+ if (signal?.aborted) return Promise.resolve(cancelledOpen())
160
+ const ac = new AbortController()
161
+ const id = headers["x-request-id"]
162
+ const h = { ...headers, "accept-encoding": "identity", "x-cursor-streaming": "true" }
163
+ let ended = false
164
+ let seq = 0
165
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
166
+ const req = new Duplex({
167
+ read() {},
168
+ write(chunk, _enc, cb) {
169
+ const msg = Buffer.from(chunk).subarray(5)
170
+ const n = seq++
171
+ append(msg, n).then(() => cb(), (e) => cb(e))
172
+ },
173
+ })
174
+ const cleanup = () => {
175
+ signal?.removeEventListener("abort", close)
176
+ ac.abort()
177
+ reader?.cancel().catch(() => {})
178
+ }
179
+ const end = (body: string) => {
180
+ if (ended || req.destroyed) return
181
+ ended = true
182
+ const f = frame(Buffer.from(body))
183
+ f[0] = 2
184
+ req.push(f)
185
+ req.push(null)
186
+ cleanup()
187
+ }
188
+ const failed = async (res: Response) => {
189
+ const text = await res.text().catch(() => "")
190
+ let e
191
+ try { e = JSON.parse(text) } catch {}
192
+ end(JSON.stringify({ error: typeof e?.code === "string" ? e : { code: connectCode(res.status), message: text.trim() || `HTTP ${res.status}` } }))
193
+ }
194
+ const append = async (msg: Buffer, n: number) => {
195
+ if (ended || ac.signal.aborted) return
196
+ const body = pb().str(1, msg.toString("hex")).bytes(2, pb().str(1, id).done()).varint(3, n).done()
197
+ const ms = H1.appendWait + Math.ceil(body.length / 65536) * 1000
198
+ const deadline = AbortSignal.timeout(ms)
199
+ try {
200
+ const res = await fetch(API + "/aiserver.v1.BidiService/BidiAppend", {
201
+ method: "POST",
202
+ headers: { ...h, "content-type": "application/proto", "connect-protocol-version": "1" },
203
+ body,
204
+ signal: AbortSignal.any([ac.signal, deadline]),
205
+ })
206
+ if (ended || ac.signal.aborted) { await res.body?.cancel().catch(() => {}); return }
207
+ if (!res.ok) return failed(res)
208
+ await res.arrayBuffer()
209
+ } catch (caught) {
210
+ const e = caught as Thrown
211
+ if (ac.signal.aborted) return
212
+ if (deadline.aborted) return end(JSON.stringify({ error: { code: "deadline_exceeded", message: `BidiAppend got no answer in ${Math.round(ms / 1000)}s` } }))
213
+ end(JSON.stringify({ error: { code: "unavailable", message: `BidiAppend: ${e?.message ?? e}` } }))
214
+ }
215
+ }
216
+ const close = () => {
217
+ ended = true
218
+ cleanup()
219
+ req.destroy()
220
+ }
221
+ signal?.addEventListener("abort", close, { once: true })
222
+ if (signal?.aborted) {
223
+ close()
224
+ return Promise.resolve(cancelledOpen())
225
+ }
226
+ ;(async () => {
227
+ try {
228
+ const res = await fetch(API + "/agent.v1.AgentService/RunSSE", {
229
+ method: "POST",
230
+ headers: { ...h, "content-type": "application/connect+proto", "connect-protocol-version": "1" },
231
+ body: frame(pb().str(1, id).done()),
232
+ signal: ac.signal,
233
+ })
234
+ if (ended || ac.signal.aborted) { await res.body?.cancel().catch(() => {}); return }
235
+ if (!res.ok) return failed(res)
236
+ reader = res.body!.getReader()
237
+ try {
238
+ while (!ended && !req.destroyed) {
239
+ const { value, done } = await reader.read()
240
+ if (done) break
241
+ if (!ended && !req.destroyed) req.push(Buffer.from(value))
242
+ }
243
+ } finally {
244
+ reader.releaseLock()
245
+ reader = undefined
246
+ }
247
+ if (!ended && !req.destroyed) {
248
+ ended = true
249
+ req.push(null)
250
+ cleanup()
251
+ }
252
+ } catch (caught) {
253
+ const e = caught as Thrown
254
+ if (!ac.signal.aborted) end(JSON.stringify({ error: { code: "unavailable", message: `RunSSE: ${e?.message ?? e}` } }))
255
+ }
256
+ })()
257
+ return Promise.resolve(signal?.aborted ? cancelledOpen() : { session: { close, destroy: close }, req: Object.assign(req, { close }), status: 200, h1: true, headers: {} })
258
+ }
259
+
260
+ export async function open({ base, tok, headers: extra, signal, connect = defaultConnect, headerWaitMs = H2.wait, version }: OpenRequest): Promise<Opened | OpenFailed> {
261
+ const headers = cursorHeaders(tok, version, extra)
262
+ if (signal?.aborted) return cancelledOpen()
263
+ if (connect !== defaultConnect) {
264
+ const o = await openH2(base, headers, signal, connect, headerWaitMs)
265
+ if (!o.error) trace?.note("transport", { url: base, h1: false })
266
+ return o
267
+ }
268
+ if (Date.now() >= h1Until) {
269
+ const o = await openH2(base, headers, signal, defaultConnect, headerWaitMs)
270
+ if (signal?.aborted) {
271
+ try { o.req?.close?.(http2.constants.NGHTTP2_CANCEL) } catch {}
272
+ try { o.session?.destroy?.() } catch {}
273
+ return cancelledOpen()
274
+ }
275
+ if (!o.h2Failed) {
276
+ trace?.note("transport", { url: base, h1: false })
277
+ return o
278
+ }
279
+ if (o.blocked) h1Until = Date.now() + H2.retryAfter
280
+ trace?.note("transport", { url: API, h1: true, h2: { url: base, error: o.error }, until: o.blocked ? h1Until : undefined })
281
+ } else trace?.note("transport", { url: API, h1: true, until: h1Until })
282
+ if (signal?.aborted) return cancelledOpen()
283
+ return openH1(headers, signal)
284
+ }
285
+
286
+ export function resetH1(): void { h1Until = 0 }
287
+
288
+ export function transportState(now: number): TransportState {
289
+ return { transport: now < h1Until ? { via: "h1", until: h1Until } : { via: "h2" } }
290
+ }