@caph42/pi-cursor-provider 0.0.0-stage → 0.3.0

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,330 @@
1
+ /**
2
+ * Cursor Run events as a Pi assistant stream.
3
+ *
4
+ * Tool calls on the stateless path stop the Run. Pi executes them and the next
5
+ * request carries the results as history.
6
+ * A same-process native Run stays open. The next turn writes matching
7
+ * call_cursor_<hex>_<seg>_<i> results back to that stream. This file only
8
+ * maps events. It does not write the tool result itself.
9
+ */
10
+ import {
11
+ calculateCost,
12
+ createAssistantMessageEventStream,
13
+ getCurrentSystemPrompt,
14
+ getCurrentTools,
15
+ } from "@earendil-works/pi-ai"
16
+ import type {
17
+ Api,
18
+ AssistantMessage,
19
+ AssistantMessageEvent,
20
+ AssistantMessageEventStream,
21
+ Model,
22
+ SimpleStreamOptions,
23
+ StopReason,
24
+ TextContent,
25
+ ThinkingContent,
26
+ ToolCall,
27
+ TranscriptContext,
28
+ Usage,
29
+ } from "@earendil-works/pi-ai"
30
+ import { resolveAccessToken } from "./auth.ts"
31
+ import { runAnswer } from "./run.ts"
32
+
33
+ /** Shown when no Cursor credential is available. */
34
+ export const CURSOR_NOT_SIGNED_IN = "Cursor isn't signed in. Run /login cursor or set CURSOR_ACCESS_TOKEN."
35
+
36
+ type RunTool = { id: string; name: string; args: string }
37
+ type RunUsage = {
38
+ prompt_tokens?: number
39
+ completion_tokens?: number
40
+ prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number }
41
+ completion_tokens_details?: { reasoning_tokens?: number }
42
+ /** Earlier steps' usage collected with this step; not applied to Pi context size. */
43
+ magpie_deferred?: {
44
+ prompt_tokens?: number
45
+ completion_tokens?: number
46
+ cached_tokens?: number
47
+ cache_write_tokens?: number
48
+ }
49
+ }
50
+ type RunEvent = {
51
+ text?: string
52
+ reasoning?: string
53
+ tool?: RunTool
54
+ stop?: string
55
+ usage?: RunUsage
56
+ error?: { status?: number; message?: string }
57
+ }
58
+
59
+ function zeroUsage(): Usage {
60
+ return {
61
+ input: 0,
62
+ output: 0,
63
+ cacheRead: 0,
64
+ cacheWrite: 0,
65
+ totalTokens: 0,
66
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
67
+ }
68
+ }
69
+
70
+ function blank(model: Model<Api>): AssistantMessage {
71
+ return {
72
+ role: "assistant",
73
+ content: [],
74
+ api: model.api,
75
+ provider: model.provider,
76
+ model: model.id,
77
+ usage: zeroUsage(),
78
+ stopReason: "pending",
79
+ timestamp: Date.now(),
80
+ }
81
+ }
82
+
83
+ function normalizeError(message: string): string {
84
+ const text = message || "Cursor request failed"
85
+ if (/rate limit|too many requests|usage limit/i.test(text)) return text
86
+ if (/context[_ ]length[_ ]exceeded|too many tokens|prompt (?:is )?too long|exceeds the context window|input is too long/i.test(text)) {
87
+ return /context[_ ]length[_ ]exceeded/i.test(text) ? text : `context_length_exceeded: ${text}`
88
+ }
89
+ return text
90
+ }
91
+
92
+ function toolArguments(raw: string): ToolCall["arguments"] {
93
+ try {
94
+ const value = JSON.parse(raw || "{}") as unknown
95
+ if (value && typeof value === "object" && !Array.isArray(value)) return value as ToolCall["arguments"]
96
+ } catch {
97
+ // The model handed back arguments that are not a JSON object.
98
+ }
99
+ return {}
100
+ }
101
+
102
+ function toChat(messages: TranscriptContext["messages"], system: string) {
103
+ const out: Record<string, unknown>[] = []
104
+ if (system) out.push({ role: "system", content: system })
105
+ for (const message of messages) {
106
+ if (message.role === "system") continue
107
+ if (message.role === "user") {
108
+ if (typeof message.content === "string") {
109
+ out.push({ role: "user", content: message.content })
110
+ continue
111
+ }
112
+ const parts: Array<{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }> = []
113
+ for (const part of message.content) {
114
+ if (part.type === "text" && part.text) parts.push({ type: "text", text: part.text })
115
+ else if (part.type === "image") {
116
+ const data = part.data.startsWith("data:") ? part.data : `data:${part.mimeType};base64,${part.data}`
117
+ parts.push({ type: "image_url", image_url: { url: data } })
118
+ }
119
+ }
120
+ if (parts.length) out.push({ role: "user", content: parts })
121
+ continue
122
+ }
123
+ if (message.role === "assistant") {
124
+ const text = message.content.filter((part): part is TextContent => part.type === "text").map((part) => part.text).join("")
125
+ const toolCalls = message.content.filter((part): part is ToolCall => part.type === "toolCall").map((part) => ({
126
+ id: part.id,
127
+ type: "function",
128
+ function: { name: part.name, arguments: JSON.stringify(part.arguments ?? {}) },
129
+ }))
130
+ if (!text && toolCalls.length === 0) continue
131
+ out.push({ role: "assistant", content: text, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) })
132
+ continue
133
+ }
134
+ if (message.role === "toolResult") {
135
+ const text = message.content.map((part) => (part.type === "text" ? part.text : "[image]")).join("")
136
+ out.push({
137
+ role: "tool",
138
+ tool_call_id: message.toolCallId,
139
+ content: text,
140
+ ...(message.isError ? { isError: true } : {}),
141
+ })
142
+ }
143
+ }
144
+ return out
145
+ }
146
+
147
+ function applyUsage(message: AssistantMessage, model: Model<Api>, usage: RunUsage | undefined) {
148
+ const cacheRead = usage?.prompt_tokens_details?.cached_tokens ?? 0
149
+ const cacheWrite = usage?.prompt_tokens_details?.cache_write_tokens ?? 0
150
+ const prompt = usage?.prompt_tokens ?? 0
151
+ const output = usage?.completion_tokens ?? 0
152
+ const input = Math.max(prompt - cacheRead - cacheWrite, 0)
153
+ const reasoning = usage?.completion_tokens_details?.reasoning_tokens
154
+ message.usage = {
155
+ input,
156
+ output,
157
+ cacheRead,
158
+ cacheWrite,
159
+ totalTokens: input + output + cacheRead + cacheWrite,
160
+ ...(typeof reasoning === "number" ? { reasoning } : {}),
161
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
162
+ }
163
+ calculateCost(model, message.usage)
164
+ }
165
+
166
+ /** Map one Run's decoded events onto a Pi assistant stream. `start` is emitted here. */
167
+ export async function emitCursorEvents(
168
+ stream: AssistantMessageEventStream,
169
+ model: Model<Api>,
170
+ events: AsyncIterable<RunEvent>,
171
+ options?: SimpleStreamOptions,
172
+ ): Promise<void> {
173
+ const message = blank(model)
174
+ if (options?.reasoning) message.thinkingLevel = options.reasoning
175
+ let finished = false
176
+ let open: { kind: "text" | "thinking"; index: number } | null = null
177
+
178
+ const push = (event: AssistantMessageEvent) => {
179
+ if (finished) return
180
+ if (event.type === "done" || event.type === "error") finished = true
181
+ stream.push(event)
182
+ }
183
+ const endOpen = () => {
184
+ if (!open) return
185
+ const block = message.content[open.index]
186
+ if (block?.type === "text") push({ type: "text_end", contentIndex: open.index, content: block.text, partial: message })
187
+ if (block?.type === "thinking") {
188
+ push({ type: "thinking_end", contentIndex: open.index, content: block.thinking, partial: message })
189
+ }
190
+ open = null
191
+ }
192
+ const fail = (reason: Extract<StopReason, "error" | "aborted">, text: string) => {
193
+ if (finished) return
194
+ endOpen()
195
+ message.stopReason = reason
196
+ message.errorMessage = text
197
+ push({ type: "error", reason, error: message })
198
+ }
199
+
200
+ push({ type: "start", partial: message })
201
+ try {
202
+ let sawTool = false
203
+ for await (const event of events) {
204
+ await options?.onProviderStreamEvent?.(event, model)
205
+ if (options?.signal?.aborted) {
206
+ fail("aborted", "the request was cancelled")
207
+ return
208
+ }
209
+ if (event.error) {
210
+ const aborted = options?.signal?.aborted || /cancelled/i.test(String(event.error.message ?? ""))
211
+ fail(aborted ? "aborted" : "error", aborted ? "the request was cancelled" : normalizeError(String(event.error.message ?? "")))
212
+ return
213
+ }
214
+ if (event.text) {
215
+ if (open?.kind === "thinking") endOpen()
216
+ if (!open) {
217
+ message.content.push({ type: "text", text: "" })
218
+ open = { kind: "text", index: message.content.length - 1 }
219
+ push({ type: "text_start", contentIndex: open.index, partial: message })
220
+ }
221
+ const block = message.content[open.index] as TextContent
222
+ block.text += event.text
223
+ push({ type: "text_delta", contentIndex: open.index, delta: event.text, partial: message })
224
+ }
225
+ if (event.reasoning) {
226
+ if (open?.kind === "text") endOpen()
227
+ if (!open) {
228
+ message.content.push({ type: "thinking", thinking: "" })
229
+ open = { kind: "thinking", index: message.content.length - 1 }
230
+ push({ type: "thinking_start", contentIndex: open.index, partial: message })
231
+ }
232
+ const block = message.content[open.index] as ThinkingContent
233
+ block.thinking += event.reasoning
234
+ push({ type: "thinking_delta", contentIndex: open.index, delta: event.reasoning, partial: message })
235
+ }
236
+ if (event.tool) {
237
+ endOpen()
238
+ sawTool = true
239
+ const call: ToolCall = {
240
+ type: "toolCall",
241
+ id: event.tool.id,
242
+ name: event.tool.name,
243
+ arguments: toolArguments(event.tool.args),
244
+ }
245
+ message.content.push(call)
246
+ const index = message.content.length - 1
247
+ push({ type: "toolcall_start", contentIndex: index, partial: message })
248
+ push({ type: "toolcall_delta", contentIndex: index, delta: JSON.stringify(call.arguments), partial: message })
249
+ push({ type: "toolcall_end", contentIndex: index, toolCall: call, partial: message })
250
+ }
251
+ if (event.stop) {
252
+ endOpen()
253
+ applyUsage(message, model, event.usage)
254
+ const reason: Extract<StopReason, "stop" | "toolUse"> = sawTool || event.stop === "tool_calls" ? "toolUse" : "stop"
255
+ message.stopReason = reason
256
+ push({ type: "done", reason, message })
257
+ return
258
+ }
259
+ }
260
+ endOpen()
261
+ message.stopReason = sawTool ? "toolUse" : "stop"
262
+ push({ type: "done", reason: message.stopReason, message })
263
+ } catch (err) {
264
+ const aborted = options?.signal?.aborted === true
265
+ fail(aborted ? "aborted" : "error", aborted ? "the request was cancelled" : normalizeError(err instanceof Error ? err.message : String(err)))
266
+ }
267
+ }
268
+
269
+ export function streamCursor(
270
+ model: Model<Api>,
271
+ context: TranscriptContext,
272
+ options?: SimpleStreamOptions,
273
+ ): AssistantMessageEventStream {
274
+ const stream = createAssistantMessageEventStream()
275
+ void pump(stream, model, context, options)
276
+ return stream
277
+ }
278
+
279
+ async function pump(
280
+ stream: AssistantMessageEventStream,
281
+ model: Model<Api>,
282
+ context: TranscriptContext,
283
+ options?: SimpleStreamOptions,
284
+ ) {
285
+ const message = blank(model)
286
+ const fail = (reason: Extract<StopReason, "error" | "aborted">, text: string) => {
287
+ message.stopReason = reason
288
+ message.errorMessage = text
289
+ stream.push({ type: "error", reason, error: message })
290
+ }
291
+ try {
292
+ if (options?.signal?.aborted) {
293
+ fail("aborted", "the request was cancelled")
294
+ return
295
+ }
296
+ const auth = await resolveAccessToken({ apiKey: options?.apiKey, env: options?.env })
297
+ if (!auth) {
298
+ fail("error", CURSOR_NOT_SIGNED_IN)
299
+ return
300
+ }
301
+ const piTools = options?.toolChoice === "none" ? [] : getCurrentTools(context.messages)
302
+ const system = getCurrentSystemPrompt(context.messages)
303
+ const ran = await runAnswer({
304
+ tok: auth.token,
305
+ model: model.id,
306
+ effort: options?.reasoning ?? "",
307
+ messages: toChat(context.messages, system),
308
+ tools: piTools.map((tool) => ({
309
+ name: tool.name,
310
+ description: tool.description ?? "",
311
+ schema: tool.parameters ?? { type: "object", properties: {} },
312
+ })),
313
+ session: options?.sessionId ?? "",
314
+ signal: options?.signal,
315
+ headers: options?.headers,
316
+ onPayload: options?.onPayload ? (payload: unknown) => options.onPayload?.(payload, model) : undefined,
317
+ onResponse: (response: { status: number; headers: Record<string, string> }) =>
318
+ options?.onResponse?.({ status: response.status, headers: response.headers }, model),
319
+ })
320
+ if (ran.error) {
321
+ const aborted = options?.signal?.aborted || /cancelled/i.test(String(ran.error.message ?? ""))
322
+ fail(aborted ? "aborted" : "error", aborted ? "the request was cancelled" : normalizeError(String(ran.error.message ?? "")))
323
+ return
324
+ }
325
+ await emitCursorEvents(stream, model, ran.events as AsyncIterable<RunEvent>, options)
326
+ } catch (err) {
327
+ const aborted = options?.signal?.aborted === true
328
+ fail(aborted ? "aborted" : "error", aborted ? "the request was cancelled" : normalizeError(err instanceof Error ? err.message : String(err)))
329
+ }
330
+ }