@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/CHANGELOG.md +24 -0
- package/README.md +26 -4
- package/package.json +13 -3
- package/src/agent-run.ts +430 -0
- package/src/auth.ts +26 -14
- package/src/cache.ts +38 -0
- package/src/client.ts +10 -12
- package/src/doctor.ts +149 -0
- package/src/endpoint.ts +68 -0
- package/src/fast.ts +6 -5
- package/src/index.ts +3 -16
- package/src/ledger.ts +63 -5
- package/src/models.ts +8 -5
- package/src/native-session.ts +44 -6
- package/src/protocol.ts +593 -0
- package/src/run.ts +74 -1180
- package/src/trace.ts +218 -0
- package/src/transport.ts +290 -0
- package/src/usage.ts +12 -6
package/src/trace.ts
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a diagnostic may print, and the decision journal that CURSOR_DEBUG turns on.
|
|
3
|
+
* A Decision holds only hosts, reasons scrubbed by reasonOf, statuses, model ids,
|
|
4
|
+
* and clock times. An Account compares fingerprints and prints as "[account]".
|
|
5
|
+
*/
|
|
6
|
+
import { AsyncLocalStorage } from "node:async_hooks"
|
|
7
|
+
import { inspect, isDeepStrictEqual } from "node:util"
|
|
8
|
+
import { tokenKey } from "./cache.ts"
|
|
9
|
+
|
|
10
|
+
/** The host and port of a URL. An endpoint is printed only in this form. */
|
|
11
|
+
export type Host = string & { readonly __brand: "Host" }
|
|
12
|
+
|
|
13
|
+
/** Error or refusal text after reasonOf scrubbed and clipped it. */
|
|
14
|
+
export type Reason = string & { readonly __brand: "Reason" }
|
|
15
|
+
|
|
16
|
+
export function hostOf(url: string): Host {
|
|
17
|
+
try {
|
|
18
|
+
return new URL(url).host as Host
|
|
19
|
+
} catch {
|
|
20
|
+
return "(unparseable URL)" as Host
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const REASON_MAX = 200
|
|
25
|
+
|
|
26
|
+
function reasonOf(cause: unknown): Reason {
|
|
27
|
+
const error = cause as { message?: unknown; code?: unknown } | null | undefined
|
|
28
|
+
let text = typeof cause === "string" ? cause : String(error?.message ?? cause ?? "")
|
|
29
|
+
const code = typeof error?.code === "string" ? error.code : ""
|
|
30
|
+
if (code && !text.includes(code)) text += ` (${code})`
|
|
31
|
+
text = text
|
|
32
|
+
.replace(/\bBearer\s+\S+/gi, "Bearer [token]")
|
|
33
|
+
.replace(/\bhttps?:\/\/[^\s"'<>()]*[^\s"'<>().,;:!?]/gi, (url) => hostOf(url))
|
|
34
|
+
.replace(/eyJ[\w-]*\.[\w-]*\.[\w-]*/g, "[token]")
|
|
35
|
+
.replace(/[0-9a-f]{32,}/gi, "[hex]")
|
|
36
|
+
.replace(/[\w-]{40,}/g, "[token]")
|
|
37
|
+
.replace(/\s+/g, " ")
|
|
38
|
+
.trim()
|
|
39
|
+
return (text.length > REASON_MAX ? text.slice(0, REASON_MAX - 1) + "…" : text) as Reason
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One access token as this process knows it. It compares and never prints. */
|
|
43
|
+
export class Account {
|
|
44
|
+
#fingerprint: string
|
|
45
|
+
private constructor(fingerprint: string) {
|
|
46
|
+
this.#fingerprint = fingerprint
|
|
47
|
+
}
|
|
48
|
+
static of(token: string): Account {
|
|
49
|
+
return new Account(tokenKey(token))
|
|
50
|
+
}
|
|
51
|
+
/** Whether a store key, or an owner's account, is this account's fingerprint. */
|
|
52
|
+
is(fingerprint: string): boolean {
|
|
53
|
+
return fingerprint === this.#fingerprint
|
|
54
|
+
}
|
|
55
|
+
same(other: Account): boolean {
|
|
56
|
+
return other.#fingerprint === this.#fingerprint
|
|
57
|
+
}
|
|
58
|
+
toString(): string {
|
|
59
|
+
return "[account]"
|
|
60
|
+
}
|
|
61
|
+
toJSON(): string {
|
|
62
|
+
return "[account]"
|
|
63
|
+
}
|
|
64
|
+
[inspect.custom](): string {
|
|
65
|
+
return "[account]"
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type Decision =
|
|
70
|
+
| { kind: "endpoint"; source: "server-config"; host: Host }
|
|
71
|
+
| { kind: "endpoint"; source: "global-fallback" | "kept-regional"; host: Host; why: Reason }
|
|
72
|
+
| { kind: "transport"; via: "h2"; host: Host }
|
|
73
|
+
| { kind: "transport"; via: "h1"; host: Host; cause: "sticky"; until: number }
|
|
74
|
+
| { kind: "transport"; via: "h1"; host: Host; cause: "h2-failed"; h2Host: Host; why: Reason; until: number | null }
|
|
75
|
+
| { kind: "native"; path: "resumed" | "created" }
|
|
76
|
+
| { kind: "native"; path: "declined" | "abandoned"; why: Reason }
|
|
77
|
+
| { kind: "owner-ended"; phase: "failed" | "cancelled" | "expired"; model: string; why: Reason }
|
|
78
|
+
| ({ kind: "retry"; rule: "region"; status: number; why: Reason } & ({ retriedOn: Host } | { notRetried: "same-host-over-h2" | "cancelled" }))
|
|
79
|
+
| { kind: "retry"; rule: "max-mode"; status: number; why: Reason; model: string }
|
|
80
|
+
| { kind: "failed"; status: number; why: Reason; bodyCut: boolean }
|
|
81
|
+
| { kind: "usage"; outcome: "refused" | "unavailable"; status: number }
|
|
82
|
+
| { kind: "usage"; outcome: "failed"; why: Reason }
|
|
83
|
+
|
|
84
|
+
/** A journaled decision. An identical neighbour in the same turn folds into count. */
|
|
85
|
+
export type Entry = Decision & { at: number; count: number }
|
|
86
|
+
|
|
87
|
+
/** One runAnswer call. Turn 0 holds decisions noted outside any turn, with no account. */
|
|
88
|
+
export type TurnLog = {
|
|
89
|
+
readonly turn: number
|
|
90
|
+
readonly started: number
|
|
91
|
+
readonly model: string
|
|
92
|
+
readonly account: Account | null
|
|
93
|
+
readonly entries: readonly Entry[]
|
|
94
|
+
/** Decisions refused after the turn kept ENTRIES of them. */
|
|
95
|
+
readonly dropped: number
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export type Trace = {
|
|
99
|
+
note<K extends Decision["kind"]>(kind: K, raw: RawFact<K>): void
|
|
100
|
+
within<T>(turn: { token: string; model?: string }, run: () => Promise<T>): Promise<T>
|
|
101
|
+
/** Keeps a stream that the turn returns inside its log. Call it inside within(). */
|
|
102
|
+
carry<E>(events: AsyncIterable<E>): AsyncIterable<E>
|
|
103
|
+
/** The last TURNS logs, oldest first, then turn 0 when it holds entries. */
|
|
104
|
+
turns(): readonly TurnLog[]
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const TURNS = 16
|
|
108
|
+
const ENTRIES = 32
|
|
109
|
+
const NO_AGENT = "GetServerConfig named no agent host"
|
|
110
|
+
|
|
111
|
+
type Failure = { status?: number; message?: string } | undefined
|
|
112
|
+
type Fields<D> = D extends unknown ? Omit<D, "kind"> : never
|
|
113
|
+
type Of<K extends Decision["kind"]> = Fields<Extract<Decision, { kind: K }>>
|
|
114
|
+
type RawFact<K extends Decision["kind"]> = Parameters<(typeof parse)[K]>[0]
|
|
115
|
+
|
|
116
|
+
const statusIn = (error: Failure) => (typeof error?.status === "number" ? error.status : 502)
|
|
117
|
+
|
|
118
|
+
// The checker does not read the files that note decisions. Each parser picks
|
|
119
|
+
// named fields and never spreads its input, so a stray token or header cannot
|
|
120
|
+
// reach a log.
|
|
121
|
+
const parse = {
|
|
122
|
+
endpoint: (raw: { url: string; listed: boolean; kept: boolean; error?: unknown }): Of<"endpoint"> =>
|
|
123
|
+
raw.listed
|
|
124
|
+
? { source: "server-config", host: hostOf(raw.url) }
|
|
125
|
+
: { source: raw.kept ? "kept-regional" : "global-fallback", host: hostOf(raw.url), why: reasonOf(raw.error ?? NO_AGENT) },
|
|
126
|
+
transport: (raw: { url: string; h1: boolean; h2?: { url: string; error: unknown }; until?: number }): Of<"transport"> => {
|
|
127
|
+
if (!raw.h1) return { via: "h2", host: hostOf(raw.url) }
|
|
128
|
+
if (!raw.h2) return { via: "h1", host: hostOf(raw.url), cause: "sticky", until: raw.until ?? 0 }
|
|
129
|
+
return { via: "h1", host: hostOf(raw.url), cause: "h2-failed", h2Host: hostOf(raw.h2.url), why: reasonOf(raw.h2.error), until: raw.until ?? null }
|
|
130
|
+
},
|
|
131
|
+
native: (raw: { path: "resumed" | "created" | "declined" | "abandoned"; fallback?: string; detail?: string; error?: unknown }): Of<"native"> => {
|
|
132
|
+
if (raw.path === "resumed" || raw.path === "created") return { path: raw.path }
|
|
133
|
+
if (raw.path === "abandoned") return { path: raw.path, why: reasonOf(raw.error) }
|
|
134
|
+
return { path: raw.path, why: reasonOf(raw.detail ? `${raw.fallback} (${raw.detail})` : raw.fallback) }
|
|
135
|
+
},
|
|
136
|
+
"owner-ended": (raw: { state: "failed" | "cancelled" | "expired"; model?: string; error: unknown }): Of<"owner-ended"> => ({
|
|
137
|
+
phase: raw.state,
|
|
138
|
+
model: String(raw.model ?? ""),
|
|
139
|
+
why: reasonOf(raw.error),
|
|
140
|
+
}),
|
|
141
|
+
retry: (raw: { rule: "region"; error: Failure; to?: string; cancelled: boolean } | { rule: "max-mode"; error: Failure; model: string }): Of<"retry"> => {
|
|
142
|
+
const status = statusIn(raw.error)
|
|
143
|
+
const why = reasonOf(raw.error)
|
|
144
|
+
if (raw.rule === "max-mode") return { rule: "max-mode", status, why, model: String(raw.model ?? "") }
|
|
145
|
+
if (raw.to) return { rule: "region", status, why, retriedOn: hostOf(raw.to) }
|
|
146
|
+
return { rule: "region", status, why, notRetried: raw.cancelled ? "cancelled" : "same-host-over-h2" }
|
|
147
|
+
},
|
|
148
|
+
failed: (raw: { error: Failure & { bodyCut?: boolean } }): Of<"failed"> => ({
|
|
149
|
+
status: statusIn(raw.error),
|
|
150
|
+
why: reasonOf(raw.error),
|
|
151
|
+
bodyCut: raw.error?.bodyCut === true,
|
|
152
|
+
}),
|
|
153
|
+
usage: (raw: { status?: number; refused?: boolean; error?: unknown }): Of<"usage"> =>
|
|
154
|
+
raw.status === undefined ? { outcome: "failed", why: reasonOf(raw.error) } : { outcome: raw.refused ? "refused" : "unavailable", status: raw.status },
|
|
155
|
+
} satisfies { [K in Decision["kind"]]: (raw: never) => Of<K> }
|
|
156
|
+
|
|
157
|
+
type Log = { turn: number; started: number; model: string; account: Account | null; entries: Entry[]; dropped: number }
|
|
158
|
+
|
|
159
|
+
function sameDecision(entry: Entry, decision: Decision): boolean {
|
|
160
|
+
const { at: _at, count: _count, ...rest } = entry
|
|
161
|
+
return isDeepStrictEqual(rest, decision)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function enabled(value: string | undefined): boolean {
|
|
165
|
+
const v = (value ?? "").trim().toLowerCase()
|
|
166
|
+
return v !== "" && !["0", "false", "off", "no"].includes(v)
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function createTrace(): Trace {
|
|
170
|
+
const scope = new AsyncLocalStorage<Log>()
|
|
171
|
+
const logs: Log[] = []
|
|
172
|
+
const outside: Log = { turn: 0, started: Date.now(), model: "", account: null, entries: [], dropped: 0 }
|
|
173
|
+
let next = 1
|
|
174
|
+
return {
|
|
175
|
+
note(kind, raw) {
|
|
176
|
+
if (!Object.hasOwn(parse, kind)) return
|
|
177
|
+
const decision = { kind, ...(parse[kind] as (raw: unknown) => object)(raw) } as Decision
|
|
178
|
+
const log = scope.getStore() ?? outside
|
|
179
|
+
const last = log.entries.at(-1)
|
|
180
|
+
const now = Date.now()
|
|
181
|
+
if (last && sameDecision(last, decision)) {
|
|
182
|
+
last.count += 1
|
|
183
|
+
last.at = now
|
|
184
|
+
} else if (log.entries.length >= ENTRIES) log.dropped += 1
|
|
185
|
+
else log.entries.push({ ...decision, at: now, count: 1 })
|
|
186
|
+
},
|
|
187
|
+
within(turn, run) {
|
|
188
|
+
const log: Log = { turn: next++, started: Date.now(), model: turn.model ?? "", account: Account.of(turn.token), entries: [], dropped: 0 }
|
|
189
|
+
logs.push(log)
|
|
190
|
+
while (logs.length > TURNS) logs.shift()
|
|
191
|
+
return scope.run(log, run)
|
|
192
|
+
},
|
|
193
|
+
// The consumer reads events after runAnswer has returned, and
|
|
194
|
+
// AsyncLocalStorage does not follow a generator into a later next().
|
|
195
|
+
carry<E>(events: AsyncIterable<E>): AsyncIterable<E> {
|
|
196
|
+
const log = scope.getStore()
|
|
197
|
+
if (!log) return events
|
|
198
|
+
const it = events[Symbol.asyncIterator]()
|
|
199
|
+
const carried: AsyncIterableIterator<E> = {
|
|
200
|
+
next: () => scope.run(log, () => it.next()),
|
|
201
|
+
return: (value?: unknown) => scope.run(log, () => it.return?.(value) ?? Promise.resolve({ done: true as const, value: undefined })),
|
|
202
|
+
[Symbol.asyncIterator]: () => carried,
|
|
203
|
+
}
|
|
204
|
+
return carried
|
|
205
|
+
},
|
|
206
|
+
turns() {
|
|
207
|
+
return outside.entries.length ? [...logs, outside] : [...logs]
|
|
208
|
+
},
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Declared after everything createTrace reads at module load.
|
|
213
|
+
export let trace: Trace | undefined = enabled(process.env.CURSOR_DEBUG) ? createTrace() : undefined
|
|
214
|
+
|
|
215
|
+
/** For tests. Swaps in a fresh, empty journal, or none. */
|
|
216
|
+
export function traceForTests(on: boolean): void {
|
|
217
|
+
trace = on ? createTrace() : undefined
|
|
218
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -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
|
+
}
|
package/src/usage.ts
CHANGED
|
@@ -9,11 +9,12 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { STATUS_CODES } from "node:http"
|
|
11
11
|
import { API, unary } from "./client.ts"
|
|
12
|
+
import { tokenKey, recall, store } from "./cache.ts"
|
|
12
13
|
|
|
13
14
|
export const WEBSITE = "https://cursor.com"
|
|
14
15
|
|
|
15
16
|
const PLAN_TTL = 3600_000
|
|
16
|
-
const plans = new Map<string, { plan: string;
|
|
17
|
+
const plans = new Map<string, { plan: string; expires: number }>()
|
|
17
18
|
|
|
18
19
|
function until(ms: number, signal?: AbortSignal): AbortSignal {
|
|
19
20
|
const deadline = AbortSignal.timeout(ms)
|
|
@@ -179,20 +180,25 @@ async function periodUsage(tok: string, ids: string[], signal?: AbortSignal): Pr
|
|
|
179
180
|
}
|
|
180
181
|
|
|
181
182
|
async function planOf(tok: string, signal?: AbortSignal): Promise<string> {
|
|
182
|
-
const
|
|
183
|
-
|
|
183
|
+
const key = tokenKey(tok)
|
|
184
|
+
const had = recall(plans, key)
|
|
185
|
+
if (had) return had.plan
|
|
184
186
|
try {
|
|
185
187
|
const body = await unary(API, "aiserver.v1.DashboardService/GetPlanInfo", tok, {}, 15_000, signal)
|
|
186
188
|
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
187
189
|
const plan = String(body?.planInfo?.planName ?? "").trim()
|
|
188
|
-
if (plan) plans
|
|
189
|
-
return plan
|
|
190
|
+
if (plan) store(plans, key, { plan, expires: 0 }, PLAN_TTL)
|
|
191
|
+
return plan
|
|
190
192
|
} catch (err) {
|
|
191
193
|
if (cancelled(signal, err)) throw err
|
|
192
|
-
return
|
|
194
|
+
return ""
|
|
193
195
|
}
|
|
194
196
|
}
|
|
195
197
|
|
|
198
|
+
export function planCacheKeys(): string[] {
|
|
199
|
+
return [...plans.keys()]
|
|
200
|
+
}
|
|
201
|
+
|
|
196
202
|
async function botUsage(tok: string, signal?: AbortSignal): Promise<UsageWindow[]> {
|
|
197
203
|
try {
|
|
198
204
|
const subject = JSON.parse(Buffer.from(tok.split(".")[1] ?? "", "base64url").toString()).sub
|