@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/CHANGELOG.md +5 -0
- package/README.md +4 -4
- package/package.json +1 -1
- package/src/agent-run.ts +430 -0
- package/src/endpoint.ts +68 -0
- package/src/fast.ts +6 -5
- package/src/native-session.ts +1 -1
- package/src/protocol.ts +593 -0
- package/src/run.ts +31 -1208
- package/src/transport.ts +290 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.2
|
|
4
|
+
|
|
5
|
+
- The `cursor-fast` status is always published with `ctx.ui.setStatus`, not only when Pi's own footer is in use. A footer that renders extension statuses — including pi-ccline, which takes the only custom-footer slot on Pi 1.4 — now shows `fast: on/off/unavailable` instead of losing it. Cursor's own footer still filters that key out, so the inline badge never appears twice.
|
|
6
|
+
|
|
3
7
|
## 0.5.1
|
|
4
8
|
|
|
5
9
|
- A stored login renews the way the Cursor IDE does: a `refresh_token` grant at `api2.cursor.sh/oauth/token`, using the stored refresh token rather than the access token. A session Cursor ends asks for `/login cursor` instead of reporting a bare HTTP status. Checked against the real service: the grant minted a new access token, and that token opened a Run, listed models, and read usage. Offline tests cover the grant, rotation, and the failures.
|
|
@@ -12,6 +16,7 @@
|
|
|
12
16
|
- A failed model refresh returns that credential's last catalog, or an empty list when it has none.
|
|
13
17
|
- Tool names, descriptions, and schemas cannot close the catalog tags.
|
|
14
18
|
- Offline tests cover assistant events, Run retries, and HTTP/2 stickiness.
|
|
19
|
+
- `run.ts` is split by seam: the agent host cache is `endpoint.ts`, the HTTP/1.1 fallback is `transport.ts`, chat encoding and `exec` are `protocol.ts`, a single Run (stateless or native) is `agent-run.ts`. `run.ts` keeps `runAnswer` and its retry rules, and it is typechecked now. The unused exec refusal counter is gone.
|
|
15
20
|
|
|
16
21
|
## 0.3.0
|
|
17
22
|
|
package/README.md
CHANGED
|
@@ -73,13 +73,13 @@ Select a Cursor model, then use:
|
|
|
73
73
|
/cursor.fast off
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
-
With no argument, `/cursor.fast` shows the current status. In the TUI, type `/cursor.fast ` and press Tab to choose `on` or `off`; a unique prefix such as `of` completes to `off` without executing the command. You can still type `/cursor.fast status` explicitly to query the status. In the TUI, `fast: on`, `fast: off`, or `fast: unavailable` appears on the second footer row beside the model/thinking information. Other extension statuses retain their own row. RPC clients continue receiving the `cursor-fast` status text. Enabling fast preserves the selected model ID, context size, and thinking level. It requires an account-available fast variant at the same context and effective thinking parameters; unsupported combinations are rejected.
|
|
76
|
+
With no argument, `/cursor.fast` shows the current status. In the TUI, type `/cursor.fast ` and press Tab to choose `on` or `off`; a unique prefix such as `of` completes to `off` without executing the command. You can still type `/cursor.fast status` explicitly to query the status. In the TUI, `fast: on`, `fast: off`, or `fast: unavailable` appears on the second footer row beside the model/thinking information. Other extension statuses retain their own row. The same text is also published through `ctx.ui.setStatus`, so a footer that renders extension statuses — Pi's own footer, or pi-ccline's — still shows it when another extension owns the footer slot; Cursor's footer filters that key out, so it never appears twice. RPC clients continue receiving the `cursor-fast` status text. Enabling fast preserves the selected model ID, context size, and thinking level. It requires an account-available fast variant at the same context and effective thinking parameters; unsupported combinations are rejected.
|
|
77
77
|
|
|
78
78
|
The setting defaults to off and belongs to the current model in the current session. Other models keep their own settings. Reloading or resuming that session restores the setting from its current branch; a new session starts with fast off. Changes apply to the next request and require the current response to finish first.
|
|
79
79
|
|
|
80
80
|
If fast is enabled and a later thinking change or catalogue update removes support, the footer shows `fast: on (unavailable)` and requests report an error until you select a supported thinking level or run `/cursor.fast off`. The command does not add duplicate fast models to `/model`.
|
|
81
81
|
|
|
82
|
-
The second-row display uses Pi 1.4's custom-footer slot and its default renderer. On other Pi versions it falls back to the standard status row until the footer adapter is verified. Extensions that replace the same footer slot can replace this layout; Cursor yields if another extension takes ownership.
|
|
82
|
+
The second-row display uses Pi 1.4's custom-footer slot and its default renderer. On other Pi versions it falls back to the standard status row until the footer adapter is verified. Extensions that replace the same footer slot can replace this layout; Cursor yields if another extension takes ownership. The `cursor-fast` status row is still set in that case, so a footer that renders extension statuses keeps showing the fast state; otherwise `/cursor.fast status` remains the source of truth.
|
|
83
83
|
|
|
84
84
|
## How this relates to other Cursor packages
|
|
85
85
|
|
|
@@ -185,9 +185,9 @@ npm test
|
|
|
185
185
|
CURSOR_E2E=1 npm run test:e2e
|
|
186
186
|
```
|
|
187
187
|
|
|
188
|
-
`npm test` stays off the Cursor network (fetch is mocked where the dashboard is involved). `npm run test:e2e` hits a real Cursor account (cursor-agent `auth.json`, `CURSOR_ACCESS_TOKEN`, or `/login cursor`) and never prints the token. The checker reads `client.ts`. `codec.ts`, `ledger.ts`, `models.ts`, `native-session.ts
|
|
188
|
+
`npm test` stays off the Cursor network (fetch is mocked where the dashboard is involved). `npm run test:e2e` hits a real Cursor account (cursor-agent `auth.json`, `CURSOR_ACCESS_TOKEN`, or `/login cursor`) and never prints the token. The checker reads `client.ts` and `run.ts`. `codec.ts`, `ledger.ts`, `models.ts`, and `native-session.ts` still keep their `// @ts-nocheck` magpie-port headers.
|
|
189
189
|
|
|
190
|
-
The renewal grant is checked against the real service: `POST api2.cursor.sh/oauth/token`
|
|
190
|
+
The renewal grant is checked against the real service: `POST api2.cursor.sh/oauth/token` answered with a new access token, and that token listed models, read usage, and completed a Run. `npm test` covers the request shape, the rotation, and the failures offline; how the server itself answers still needs a live check.
|
|
191
191
|
|
|
192
192
|
## License
|
|
193
193
|
|
package/package.json
CHANGED
package/src/agent-run.ts
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
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 { EMPTY, failure, frame, frames, pb } from "./codec.ts"
|
|
8
|
+
import { clientVersion } from "./client.ts"
|
|
9
|
+
import { canRead, ledger, owe, STEP_WAIT, usageKey } from "./ledger.ts"
|
|
10
|
+
import { NATIVE_LIMITS, NativeSessionError, nativeSessions } from "./native-session.ts"
|
|
11
|
+
import { buildRun, decode, exec, usageOf, type BlobStore, type ChatTool, type Conversation, type Frame, type ModelParam, type Payload, type RunError, type RunEvent } from "./protocol.ts"
|
|
12
|
+
import { cancelledOpen, open, type Connect, type RunStream } from "./transport.ts"
|
|
13
|
+
import { trace } from "./trace.ts"
|
|
14
|
+
|
|
15
|
+
export type RunArgs = {
|
|
16
|
+
tok: string
|
|
17
|
+
base: string
|
|
18
|
+
id: string
|
|
19
|
+
maxMode: boolean
|
|
20
|
+
params: readonly ModelParam[]
|
|
21
|
+
tools: readonly ChatTool[]
|
|
22
|
+
conv: Conversation
|
|
23
|
+
/** "" without a session: the Run gets an id of its own. */
|
|
24
|
+
convID: string
|
|
25
|
+
signal?: AbortSignal
|
|
26
|
+
connect?: Connect
|
|
27
|
+
onResponse?: (response: { status: number; headers: Record<string, string> }) => unknown
|
|
28
|
+
onPayload?: (payload: Payload) => unknown
|
|
29
|
+
headers?: Record<string, string | null | undefined>
|
|
30
|
+
headerWaitMs?: number
|
|
31
|
+
toolIdleMs?: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A Run's events, or the error it ended on. h1: the Run went over HTTP/1.1. */
|
|
35
|
+
export type RunResult =
|
|
36
|
+
| { error: RunError & { bodyCut?: boolean; retentionIneligible?: boolean }; h1?: boolean; conversationId?: undefined; events?: undefined }
|
|
37
|
+
| { error?: undefined; conversationId: string; h1?: boolean; events: AsyncIterable<RunEvent> }
|
|
38
|
+
|
|
39
|
+
export type Prepared = { owner: NativeOwner } | { owner?: undefined; fallback?: string }
|
|
40
|
+
|
|
41
|
+
type Thrown = { status?: number; message?: string }
|
|
42
|
+
|
|
43
|
+
type SegmentEvents = {
|
|
44
|
+
next(): Promise<IteratorResult<RunEvent>>
|
|
45
|
+
return(): Promise<IteratorResult<RunEvent>>
|
|
46
|
+
[Symbol.asyncIterator](): SegmentEvents
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type NativeTransport = {
|
|
50
|
+
outbound: { bytes: number; messages: number }
|
|
51
|
+
send(message: Buffer): void
|
|
52
|
+
room(size: number): Promise<void>
|
|
53
|
+
close(): void
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type NativeAccounting = {
|
|
57
|
+
started(): void
|
|
58
|
+
settle(): Promise<unknown>
|
|
59
|
+
delivered(): void
|
|
60
|
+
abandon(): void
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
type NativeOwner = {
|
|
64
|
+
accounting?: NativeAccounting
|
|
65
|
+
chatTools?: readonly ChatTool[]
|
|
66
|
+
pumpTask?: Promise<void>
|
|
67
|
+
readonly error?: RunError & { retentionIneligible?: boolean }
|
|
68
|
+
readonly ac: AbortController
|
|
69
|
+
readonly limits: typeof NATIVE_LIMITS
|
|
70
|
+
readonly segments: number
|
|
71
|
+
readonly finalUsage?: unknown
|
|
72
|
+
attach(signal?: AbortSignal): void
|
|
73
|
+
fail(error: { status: number; message?: string }): void
|
|
74
|
+
bind(transport: NativeTransport, blobs: BlobStore, estimate: number): void
|
|
75
|
+
send(message: Buffer): void
|
|
76
|
+
pump(stream: AsyncIterable<Frame>): Promise<void>
|
|
77
|
+
response(): { events: SegmentEvents }
|
|
78
|
+
resume(prepared: object, signal?: AbortSignal): { events: SegmentEvents }
|
|
79
|
+
cancel(message: string): Promise<void>
|
|
80
|
+
delivered(): void
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function startRun(prepared: Prepared, args: RunArgs): Promise<RunResult> {
|
|
84
|
+
const { id, maxMode, params, signal } = args
|
|
85
|
+
const made = nativeSessions.create(prepared, { id, maxMode, params }, { pb, exec, usageOf, failure, trace })
|
|
86
|
+
const native: NativeOwner | null = made.fallback ? null : made
|
|
87
|
+
trace?.note("native", native ? { path: "created" } : { path: "declined", fallback: made.fallback, detail: made.detail })
|
|
88
|
+
let response = native ? await runNative({ ...args, native }) : await runOnce(args)
|
|
89
|
+
if (response.error?.retentionIneligible && !signal?.aborted) {
|
|
90
|
+
trace?.note("native", { path: "abandoned", error: response.error })
|
|
91
|
+
response = await runOnce(args)
|
|
92
|
+
}
|
|
93
|
+
return response
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Writes the caller's tool results to the native Run that asked for them. Throws when the owner refuses them. */
|
|
97
|
+
export function resumeRun(prepared: { owner: NativeOwner }, estimate: number, signal?: AbortSignal): AsyncIterable<RunEvent> {
|
|
98
|
+
const resumed = prepared.owner.resume({ ...prepared, estimate }, signal)
|
|
99
|
+
trace?.note("native", { path: "resumed" })
|
|
100
|
+
return withDelivery(prepared.owner, resumed.events)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function runOnce({ tok, base, id, tools, conv, convID, signal, maxMode, params, connect, onResponse, onPayload, headers, headerWaitMs, toolIdleMs }: RunArgs): Promise<RunResult> {
|
|
104
|
+
const cid = convID || randomUUID()
|
|
105
|
+
const since = Date.now()
|
|
106
|
+
const book = ledger(tok, cid, since, signal, !!convID)
|
|
107
|
+
let modelId = id
|
|
108
|
+
if (onPayload) {
|
|
109
|
+
const replaced = await onPayload({ model: modelId, maxMode: !!maxMode, params, conversationId: cid, tools: tools.map((t) => t.name) })
|
|
110
|
+
if (replaced && typeof replaced === "object" && !Buffer.isBuffer(replaced) && "model" in replaced && typeof replaced.model === "string" && replaced.model) {
|
|
111
|
+
modelId = replaced.model
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const { first, blobs } = buildRun(conv.msgs, conv.last, tools, modelId, cid, { maxMode, params })
|
|
115
|
+
const version = await clientVersion()
|
|
116
|
+
const o = await open({ base, tok, headers, version, signal, connect, headerWaitMs })
|
|
117
|
+
if (o.error) return book.done(), { ...o, h1: !!o.h1 }
|
|
118
|
+
if (onResponse) await onResponse({ status: o.status, headers: o.headers ?? {} })
|
|
119
|
+
const { session, req } = o
|
|
120
|
+
let closed = false
|
|
121
|
+
const send = (msg: Buffer) => {
|
|
122
|
+
if (!closed && !req.destroyed && req.writable) req.write(frame(msg))
|
|
123
|
+
}
|
|
124
|
+
const heartbeat = setInterval(() => send(pb().bytes(7, EMPTY).done()), 5000)
|
|
125
|
+
heartbeat.unref?.()
|
|
126
|
+
const close = () => {
|
|
127
|
+
if (closed) return
|
|
128
|
+
closed = true
|
|
129
|
+
clearInterval(heartbeat)
|
|
130
|
+
try {
|
|
131
|
+
req.close(http2.constants.NGHTTP2_CANCEL)
|
|
132
|
+
} catch {}
|
|
133
|
+
try {
|
|
134
|
+
session.close()
|
|
135
|
+
} catch {}
|
|
136
|
+
setTimeout(() => {
|
|
137
|
+
try {
|
|
138
|
+
session.destroy()
|
|
139
|
+
} catch {}
|
|
140
|
+
}, 1000).unref?.()
|
|
141
|
+
}
|
|
142
|
+
signal?.addEventListener("abort", close, { once: true })
|
|
143
|
+
if (signal?.aborted) {
|
|
144
|
+
close()
|
|
145
|
+
book.done()
|
|
146
|
+
return cancelledOpen()
|
|
147
|
+
}
|
|
148
|
+
send(first)
|
|
149
|
+
if (o.status < 200 || o.status > 299) {
|
|
150
|
+
const chunks: Buffer[] = []
|
|
151
|
+
let bodyCut = false
|
|
152
|
+
try {
|
|
153
|
+
for await (const c of req) chunks.push(c)
|
|
154
|
+
} catch {
|
|
155
|
+
bodyCut = true
|
|
156
|
+
}
|
|
157
|
+
close()
|
|
158
|
+
book.done()
|
|
159
|
+
const error = failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20))
|
|
160
|
+
return { error: bodyCut ? { ...error, bodyCut } : error, h1: !!o.h1 }
|
|
161
|
+
}
|
|
162
|
+
const it = decode(frames(req), {
|
|
163
|
+
send,
|
|
164
|
+
blobs,
|
|
165
|
+
tools,
|
|
166
|
+
estimate: conv.estimate,
|
|
167
|
+
close,
|
|
168
|
+
stepUsage: book.own,
|
|
169
|
+
owedUsage: book.owed,
|
|
170
|
+
toolIdleMs,
|
|
171
|
+
})
|
|
172
|
+
const wrapped = (async function* () {
|
|
173
|
+
try {
|
|
174
|
+
yield* it
|
|
175
|
+
} finally {
|
|
176
|
+
close()
|
|
177
|
+
book.done()
|
|
178
|
+
}
|
|
179
|
+
})()
|
|
180
|
+
const head = await wrapped.next()
|
|
181
|
+
if (head.done) return book.done(), { error: { status: 502, message: "an empty reply" }, h1: !!o.h1 }
|
|
182
|
+
if (head.value?.error) {
|
|
183
|
+
await wrapped.return?.()
|
|
184
|
+
return { error: head.value.error, h1: !!o.h1 }
|
|
185
|
+
}
|
|
186
|
+
return {
|
|
187
|
+
conversationId: cid,
|
|
188
|
+
h1: !!o.h1,
|
|
189
|
+
events: (async function* () {
|
|
190
|
+
yield head.value
|
|
191
|
+
yield* wrapped
|
|
192
|
+
})(),
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function withDelivery(owner: { delivered(): void }, events: SegmentEvents): AsyncIterableIterator<RunEvent> {
|
|
197
|
+
const it = events[Symbol.asyncIterator]()
|
|
198
|
+
return {
|
|
199
|
+
async next() {
|
|
200
|
+
const r = await it.next()
|
|
201
|
+
if (r.value?.stop) owner.delivered()
|
|
202
|
+
return r
|
|
203
|
+
},
|
|
204
|
+
return: () => it.return?.(),
|
|
205
|
+
[Symbol.asyncIterator]() { return this },
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function nativeTransport(req: RunStream, close: () => void, fail: (e: unknown) => void, limits = NATIVE_LIMITS): NativeTransport {
|
|
210
|
+
const outbound = { bytes: 0, messages: 0 }
|
|
211
|
+
const queue: Buffer[] = []
|
|
212
|
+
let closed = false, flushing = false, rejectWrite: ((error: unknown) => void) | undefined
|
|
213
|
+
type Waiter = { size: number; done(): void; timer?: ReturnType<typeof setTimeout> }
|
|
214
|
+
const waiters = new Set<Waiter>()
|
|
215
|
+
const spare = (n: number) => Math.floor(n / 8)
|
|
216
|
+
const fits = (size: number) => outbound.messages === 0 || (outbound.messages + 1 + spare(limits.outboundMessages) <= limits.outboundMessages
|
|
217
|
+
&& outbound.bytes + size + spare(limits.outboundBytes) <= limits.outboundBytes)
|
|
218
|
+
const wake = () => {
|
|
219
|
+
for (const w of waiters) if (closed || fits(w.size)) w.done()
|
|
220
|
+
}
|
|
221
|
+
const flush = async () => {
|
|
222
|
+
if (closed || flushing) return
|
|
223
|
+
flushing = true
|
|
224
|
+
try {
|
|
225
|
+
while (!closed && queue.length) {
|
|
226
|
+
const packet = queue.shift()!
|
|
227
|
+
await new Promise<void>((resolve, reject) => {
|
|
228
|
+
let written = false, drained = false, started = false, settled = false
|
|
229
|
+
const finish = (error?: unknown) => {
|
|
230
|
+
if (settled) return
|
|
231
|
+
settled = true
|
|
232
|
+
rejectWrite = undefined
|
|
233
|
+
req.removeListener("drain", drain)
|
|
234
|
+
req.removeListener("error", failed)
|
|
235
|
+
req.removeListener("close", lost)
|
|
236
|
+
error ? reject(error) : resolve()
|
|
237
|
+
}
|
|
238
|
+
const check = () => { if (started && written && drained) finish() }
|
|
239
|
+
const drain = () => { drained = true; check() }
|
|
240
|
+
const failed = (e: unknown) => finish(e)
|
|
241
|
+
const lost = () => finish(new NativeSessionError(502, "native transport closed during a write; its outcome is uncertain"))
|
|
242
|
+
rejectWrite = finish
|
|
243
|
+
req.once("drain", drain)
|
|
244
|
+
req.once("error", failed)
|
|
245
|
+
req.once("close", lost)
|
|
246
|
+
try {
|
|
247
|
+
drained = req.write(packet, (e) => {
|
|
248
|
+
if (e) return finish(e)
|
|
249
|
+
written = true
|
|
250
|
+
check()
|
|
251
|
+
}) || drained
|
|
252
|
+
started = true
|
|
253
|
+
if (drained) req.removeListener("drain", drain)
|
|
254
|
+
check()
|
|
255
|
+
} catch (e) { finish(e) }
|
|
256
|
+
})
|
|
257
|
+
if (!closed) { outbound.bytes -= packet.length; outbound.messages--; wake() }
|
|
258
|
+
}
|
|
259
|
+
} catch (e) {
|
|
260
|
+
if (!closed) fail(e)
|
|
261
|
+
} finally { flushing = false }
|
|
262
|
+
}
|
|
263
|
+
return {
|
|
264
|
+
outbound,
|
|
265
|
+
send(message) {
|
|
266
|
+
if (closed || req.destroyed || !req.writable) throw new NativeSessionError(502, "native transport is no longer writable")
|
|
267
|
+
const size = message.length + 5
|
|
268
|
+
if (outbound.bytes + size > limits.outboundBytes) throw new NativeSessionError(503, "native outbound bytes limit reached")
|
|
269
|
+
if (outbound.messages + 1 > limits.outboundMessages) throw new NativeSessionError(503, "native outbound messages limit reached")
|
|
270
|
+
outbound.bytes += size
|
|
271
|
+
outbound.messages++
|
|
272
|
+
queue.push(frame(message))
|
|
273
|
+
void flush()
|
|
274
|
+
},
|
|
275
|
+
room(size) {
|
|
276
|
+
if (closed || fits(size)) return Promise.resolve()
|
|
277
|
+
return new Promise((resolve, reject) => {
|
|
278
|
+
const w: Waiter = {
|
|
279
|
+
size,
|
|
280
|
+
done() {
|
|
281
|
+
waiters.delete(w)
|
|
282
|
+
clearTimeout(w.timer)
|
|
283
|
+
resolve()
|
|
284
|
+
},
|
|
285
|
+
}
|
|
286
|
+
w.timer = setTimeout(() => {
|
|
287
|
+
waiters.delete(w)
|
|
288
|
+
const which = outbound.bytes + size + spare(limits.outboundBytes) > limits.outboundBytes ? "bytes" : "messages"
|
|
289
|
+
reject(new NativeSessionError(503, `native outbound ${which} limit reached: the queue did not drain for ${Math.round(limits.writeWait / 1000)}s`))
|
|
290
|
+
}, limits.writeWait)
|
|
291
|
+
w.timer.unref?.()
|
|
292
|
+
waiters.add(w)
|
|
293
|
+
})
|
|
294
|
+
},
|
|
295
|
+
close() {
|
|
296
|
+
if (closed) return
|
|
297
|
+
closed = true
|
|
298
|
+
queue.length = 0
|
|
299
|
+
outbound.bytes = 0
|
|
300
|
+
outbound.messages = 0
|
|
301
|
+
wake()
|
|
302
|
+
rejectWrite?.(new NativeSessionError(410, "native transport was cancelled"))
|
|
303
|
+
close()
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function runNative({ tok, base, id, tools, conv, convID, signal, maxMode, params, native, connect, onResponse, onPayload, headers, headerWaitMs }: RunArgs & { native: NativeOwner }): Promise<RunResult> {
|
|
309
|
+
const cid = convID || randomUUID()
|
|
310
|
+
const since = Date.now()
|
|
311
|
+
const accounting = new AbortController()
|
|
312
|
+
const book = ledger(tok, cid, since, accounting.signal, !!convID, { before: since })
|
|
313
|
+
const debtKey = usageKey(tok, cid)
|
|
314
|
+
let started = false, settled = false
|
|
315
|
+
let deferred: Awaited<ReturnType<typeof book.owed>> = null
|
|
316
|
+
native.accounting = {
|
|
317
|
+
started() { started = true },
|
|
318
|
+
async settle() {
|
|
319
|
+
const more = await book.owed(true)
|
|
320
|
+
if (settled) {
|
|
321
|
+
if (more) owe(debtKey, { carry: more })
|
|
322
|
+
return null
|
|
323
|
+
}
|
|
324
|
+
deferred = more
|
|
325
|
+
return more
|
|
326
|
+
},
|
|
327
|
+
delivered() {
|
|
328
|
+
if (settled) return
|
|
329
|
+
settled = true
|
|
330
|
+
deferred = null
|
|
331
|
+
book.done()
|
|
332
|
+
accounting.abort()
|
|
333
|
+
},
|
|
334
|
+
abandon() {
|
|
335
|
+
if (settled) return
|
|
336
|
+
settled = true
|
|
337
|
+
book.done()
|
|
338
|
+
accounting.abort()
|
|
339
|
+
if (deferred) owe(debtKey, { carry: deferred })
|
|
340
|
+
deferred = null
|
|
341
|
+
if (started && native.segments > 0 && !native.finalUsage && convID && canRead(tok)) {
|
|
342
|
+
owe(debtKey, { since, n: 1, ready: Date.now() + STEP_WAIT.owedAt })
|
|
343
|
+
}
|
|
344
|
+
},
|
|
345
|
+
}
|
|
346
|
+
let modelId = id
|
|
347
|
+
if (onPayload) {
|
|
348
|
+
const replaced = await onPayload({ model: modelId, maxMode: !!maxMode, params, conversationId: cid, tools: tools.map((t) => t.name) })
|
|
349
|
+
if (replaced && typeof replaced === "object" && !Buffer.isBuffer(replaced) && "model" in replaced && typeof replaced.model === "string" && replaced.model) {
|
|
350
|
+
modelId = replaced.model
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
const { first, blobs } = buildRun(conv.msgs, conv.last, tools, modelId, cid, { maxMode, params })
|
|
354
|
+
native.chatTools = tools
|
|
355
|
+
native.attach(signal)
|
|
356
|
+
if (native.error) {
|
|
357
|
+
nativeSessions.forget(native)
|
|
358
|
+
return { error: native.error }
|
|
359
|
+
}
|
|
360
|
+
const version = await clientVersion()
|
|
361
|
+
const o = await open({ base, tok, headers, version, signal: native.ac.signal, connect, headerWaitMs })
|
|
362
|
+
if (o.error) {
|
|
363
|
+
native.fail(o.error)
|
|
364
|
+
nativeSessions.forget(native)
|
|
365
|
+
return { ...o, h1: !!o.h1 }
|
|
366
|
+
}
|
|
367
|
+
if (onResponse) await onResponse({ status: o.status, headers: o.headers ?? {} })
|
|
368
|
+
const { session, req } = o
|
|
369
|
+
const close = () => {
|
|
370
|
+
try { req.close(http2.constants.NGHTTP2_CANCEL) } catch {}
|
|
371
|
+
try { session.close() } catch {}
|
|
372
|
+
try { session.destroy() } catch {}
|
|
373
|
+
}
|
|
374
|
+
const transport = nativeTransport(req, close, (caught) => {
|
|
375
|
+
const e = caught as Thrown
|
|
376
|
+
native.fail({ status: e.status ?? 502, message: e.message })
|
|
377
|
+
}, native.limits)
|
|
378
|
+
try {
|
|
379
|
+
native.bind(transport, blobs, conv.estimate)
|
|
380
|
+
if (native.error) {
|
|
381
|
+
nativeSessions.forget(native)
|
|
382
|
+
return { error: native.error, h1: !!o.h1 }
|
|
383
|
+
}
|
|
384
|
+
native.send(first)
|
|
385
|
+
native.accounting.started()
|
|
386
|
+
if (o.status < 200 || o.status > 299) {
|
|
387
|
+
const chunks: Buffer[] = []
|
|
388
|
+
for await (const c of req) chunks.push(c)
|
|
389
|
+
native.fail(failure(o.status, Buffer.concat(chunks).toString("utf8").slice(0, 1 << 20)))
|
|
390
|
+
nativeSessions.forget(native)
|
|
391
|
+
return { error: native.error!, h1: !!o.h1 }
|
|
392
|
+
}
|
|
393
|
+
native.pumpTask = (async () => {
|
|
394
|
+
await native.pump(frames(req))
|
|
395
|
+
})()
|
|
396
|
+
const response = native.response()
|
|
397
|
+
const it = response.events
|
|
398
|
+
const head = await it.next()
|
|
399
|
+
if (head.done || head.value.error) {
|
|
400
|
+
const error = head.value?.error ?? { status: 502, message: "an empty reply" }
|
|
401
|
+
await native.cancel(error.message)
|
|
402
|
+
nativeSessions.forget(native)
|
|
403
|
+
return { error, h1: !!o.h1 }
|
|
404
|
+
}
|
|
405
|
+
let firstEvent: IteratorResult<RunEvent> | null = head
|
|
406
|
+
const events: AsyncIterableIterator<RunEvent> = {
|
|
407
|
+
next() {
|
|
408
|
+
if (firstEvent) {
|
|
409
|
+
const r = firstEvent
|
|
410
|
+
firstEvent = null
|
|
411
|
+
if (r.value?.stop) native.delivered()
|
|
412
|
+
return Promise.resolve(r)
|
|
413
|
+
}
|
|
414
|
+
return it.next().then((r) => {
|
|
415
|
+
if (r.value?.stop) native.delivered()
|
|
416
|
+
return r
|
|
417
|
+
})
|
|
418
|
+
},
|
|
419
|
+
return: () => it.return(),
|
|
420
|
+
[Symbol.asyncIterator]() { return this },
|
|
421
|
+
}
|
|
422
|
+
return { conversationId: cid, events, h1: !!o.h1 }
|
|
423
|
+
} catch (caught) {
|
|
424
|
+
const e = caught as Thrown
|
|
425
|
+
native.fail({ status: e.status ?? 502, message: e.message })
|
|
426
|
+
await native.pumpTask
|
|
427
|
+
nativeSessions.forget(native)
|
|
428
|
+
return { error: native.error!, h1: !!o.h1 }
|
|
429
|
+
}
|
|
430
|
+
}
|
package/src/endpoint.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ported from magpie's Cursor provider (MIT):
|
|
3
|
+
* https://github.com/magpie-community/plugins/tree/main/packages/cursor
|
|
4
|
+
*/
|
|
5
|
+
import { AGENT, API, unary } from "./client.ts"
|
|
6
|
+
import { recall, store, tokenKey } from "./cache.ts"
|
|
7
|
+
import { hostOf, trace, type Account, type Host } from "./trace.ts"
|
|
8
|
+
|
|
9
|
+
type Endpoint = { url: string; listed: boolean; expires: number }
|
|
10
|
+
const endpoints = new Map<string, Endpoint>()
|
|
11
|
+
const ENDPOINT_TTL = 10 * 60 * 1000
|
|
12
|
+
const ENDPOINT_MISS_TTL = 60_000
|
|
13
|
+
|
|
14
|
+
export function endpointCacheKeys(): string[] {
|
|
15
|
+
return [...endpoints.keys()]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function agentURL(tok: string, fresh: boolean, signal?: AbortSignal): Promise<string> {
|
|
19
|
+
const key = tokenKey(tok)
|
|
20
|
+
const had = recall(endpoints, key)
|
|
21
|
+
if (!fresh && had) return had.url
|
|
22
|
+
let url = AGENT
|
|
23
|
+
let listed = false
|
|
24
|
+
let error: unknown
|
|
25
|
+
try {
|
|
26
|
+
const cfg = await unary(API, "aiserver.v1.ServerConfigService/GetServerConfig", tok, {}, 10_000, signal)
|
|
27
|
+
for (const raw of [cfg?.agentUrlConfig?.agentUrl, cfg?.agentUrlConfig?.agentnUrl]) {
|
|
28
|
+
try {
|
|
29
|
+
const u = new URL(raw)
|
|
30
|
+
if ((u.protocol === "https:" || u.protocol === "http:") && u.host) {
|
|
31
|
+
url = raw.replace(/\/+$/, "")
|
|
32
|
+
listed = true
|
|
33
|
+
break
|
|
34
|
+
}
|
|
35
|
+
} catch {}
|
|
36
|
+
}
|
|
37
|
+
} catch (e) {
|
|
38
|
+
if (signal?.aborted) throw e
|
|
39
|
+
error = e
|
|
40
|
+
}
|
|
41
|
+
if (signal?.aborted) throw Object.assign(new Error("The operation was aborted"), { name: "AbortError" })
|
|
42
|
+
const kept = !listed && fresh && !!had?.url
|
|
43
|
+
trace?.note("endpoint", { url: kept ? had.url : url, listed, kept, error })
|
|
44
|
+
if (kept) return had.url
|
|
45
|
+
store(endpoints, key, { url, listed, expires: 0 }, listed ? ENDPOINT_TTL : ENDPOINT_MISS_TTL)
|
|
46
|
+
return url
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function clearAgentCache(): void {
|
|
50
|
+
endpoints.clear()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type AgentHit = {
|
|
54
|
+
host: Host
|
|
55
|
+
source: "server-config" | "global-fallback"
|
|
56
|
+
until: number
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function endpointView(account: Account | undefined, now: number): { agent: AgentHit | null; otherAgents: number } {
|
|
60
|
+
let agent: AgentHit | null = null
|
|
61
|
+
let otherAgents = 0
|
|
62
|
+
for (const [key, entry] of endpoints) {
|
|
63
|
+
if (now >= entry.expires) continue
|
|
64
|
+
if (account?.is(key)) agent = { host: hostOf(entry.url), source: entry.listed ? "server-config" : "global-fallback", until: entry.expires }
|
|
65
|
+
else otherAgents++
|
|
66
|
+
}
|
|
67
|
+
return { agent, otherAgents }
|
|
68
|
+
}
|
package/src/fast.ts
CHANGED
|
@@ -31,11 +31,12 @@ export function registerCursorFast(pi: ExtensionAPI) {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
function display(ctx: ExtensionContext, text: string | undefined) {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
ctx.ui.setStatus(STATUS,
|
|
34
|
+
// Publish the status unconditionally: footers that render extension statuses
|
|
35
|
+
// (pi-ccline, or Pi's own footer before 1.4) show it even when another
|
|
36
|
+
// extension owns the footer slot. Our own footer filters this key out
|
|
37
|
+
// (fast-footer.ts), so the inline badge is never duplicated.
|
|
38
|
+
ctx.ui.setStatus(STATUS, text)
|
|
39
|
+
if (ctx.mode !== "tui" || !supportsInlineFastFooter) return
|
|
39
40
|
if (!text) { clearFooter(); return }
|
|
40
41
|
badge = text
|
|
41
42
|
if (!footerInstalled && !footerYielded) {
|
package/src/native-session.ts
CHANGED
|
@@ -936,7 +936,7 @@ class NativeSession {
|
|
|
936
936
|
}
|
|
937
937
|
break
|
|
938
938
|
case 2: {
|
|
939
|
-
const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id),
|
|
939
|
+
const c = exec(m.data, this.chatTools, (b) => this.send(b), (id) => this.execClose(id), true)
|
|
940
940
|
if (c) this.acceptCall(c)
|
|
941
941
|
// request_context is Cursor asking for the environment, not a call
|
|
942
942
|
else if (!nativeFields(m.data).some((e) => e.num === 10)) this.answeredCall()
|