@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.
@@ -0,0 +1,593 @@
1
+ /**
2
+ * Ported from magpie's Cursor provider (MIT):
3
+ * https://github.com/magpie-community/plugins/tree/main/packages/cursor
4
+ * which itself was ported from magpie's Go client (internal/provider/cursor*.go).
5
+ */
6
+ import { createHash, randomBytes, randomUUID } from "node:crypto"
7
+ import { isDeepStrictEqual } from "node:util"
8
+ import { EMPTY, failure, field, fields, pb, pbAny, pbNum, pbStr, pbValue } from "./codec.ts"
9
+ import { CALL, GOOS, NAMESPACE, tempDir } from "./client.ts"
10
+ import { NativeSessionError, nativeFields, nativeMcpArgs } from "./native-session.ts"
11
+
12
+ /** A tool decode and exec accept. schemaText may be absent. A missing one stays missing. */
13
+ export type ExecTool = { name: string; description?: string; schema?: unknown; schemaText?: string }
14
+
15
+ export type ChatTool = { name: string; description: string; schema: unknown; schemaText: string }
16
+
17
+ export type Conversation = { msgs: Buffer[]; last: string; estimate: number }
18
+
19
+ export type BlobStore = Map<string, Buffer>
20
+
21
+ /** One frame of a Connect stream: a message, or, with end, the stream's closing JSON. */
22
+ export type Frame = { end?: boolean; data: Buffer }
23
+
24
+ export type ModelParam = { id: string; value: string }
25
+
26
+ /** One model call's usage as magpie counts it. input is the prompt's uncached rest. */
27
+ export type UsageCounts = { input: number; output: number; cacheRead: number; cacheWrite: number; reasoning: number }
28
+
29
+ export type RunError = { status: number; message: string }
30
+
31
+ export type RunUsage = {
32
+ prompt_tokens: number
33
+ completion_tokens: number
34
+ total_tokens: number
35
+ prompt_tokens_details: { cached_tokens: number; cache_write_tokens: number }
36
+ completion_tokens_details?: { reasoning_tokens: number }
37
+ /** Earlier steps' usage collected with this one. It is not this step's context size. */
38
+ magpie_deferred?: { prompt_tokens: number; completion_tokens: number; cached_tokens: number; cache_write_tokens: number }
39
+ magpie_native?: { accounting: "pending" | "estimated" | "replayed" }
40
+ }
41
+
42
+ /** What a Run streams to the caller. Each event sets one of text, reasoning, tool, stop, or error. */
43
+ export type RunEvent = {
44
+ text?: string
45
+ reasoning?: string
46
+ tool?: ToolCall & { index: number }
47
+ stop?: "stop" | "tool_calls"
48
+ usage?: RunUsage
49
+ error?: RunError
50
+ }
51
+
52
+ export type ToolCall = { id: string; name: string; args: string }
53
+
54
+ export type NativeCall = { requestID: number; execID: string; nativeID: string; name: string; args: string }
55
+
56
+ /** What onPayload is shown before a Run's request is written. A model it hands back is asked for instead. */
57
+ export type Payload = { model: string; maxMode: boolean; params: readonly ModelParam[]; conversationId: string; tools: string[] }
58
+
59
+ type Field = ReturnType<typeof fields>[number]
60
+ type ChatPart = { type?: string; text?: string; image_url?: string | { url?: string }; file?: { filename?: string } }
61
+ type ChatCall = { id: string; type?: string; function?: { name?: string; arguments?: string } }
62
+ type ChatMessage = {
63
+ role?: string
64
+ content?: string | readonly ChatPart[] | null
65
+ tool_calls?: readonly ChatCall[]
66
+ tool_call_id?: string
67
+ is_error?: unknown
68
+ isError?: unknown
69
+ }
70
+ type FunctionTool = { type?: string; function?: { name?: string; description?: string; parameters?: unknown } }
71
+
72
+ const NO_RESULT = "Tool use was interrupted and did not produce a result."
73
+ const TOOL_IDLE_MS = 3_000
74
+
75
+ const textOf = (c: unknown): string =>
76
+ typeof c === "string" ? c : Array.isArray(c) ? c.filter((p) => p?.type === "text").map((p) => p.text ?? "").join("") : ""
77
+
78
+ // joinSplitCalls joins an assistant message onto the assistant message
79
+ // before it when that one made tool calls: Anthropic takes consecutive
80
+ // assistant messages as one turn, and an agent can send a turn's parallel
81
+ // calls split over two of them, answered together after (yetone/magpie#1275).
82
+ // Answered at the second message, the first calls would be marked
83
+ // interrupted and their real results dropped. msgs is left as it is.
84
+ function joinSplitCalls(msgs: readonly ChatMessage[]): ChatMessage[] {
85
+ const out: ChatMessage[] = []
86
+ for (const m of msgs) {
87
+ const prev = out.at(-1)
88
+ if (m?.role === "assistant" && prev?.role === "assistant" && prev.tool_calls?.length) {
89
+ const content = [textOf(prev.content), textOf(m.content)].filter(Boolean).join("\n\n")
90
+ out[out.length - 1] = { ...prev, content, tool_calls: [...prev.tool_calls, ...(m.tool_calls ?? [])] }
91
+ continue
92
+ }
93
+ out.push(m)
94
+ }
95
+ return out
96
+ }
97
+
98
+ function parseArgs(s: unknown): object {
99
+ if (s && typeof s === "object") return s
100
+ try {
101
+ const v = JSON.parse((s as string) || "{}")
102
+ return v && typeof v === "object" ? v : {}
103
+ } catch {
104
+ return {}
105
+ }
106
+ }
107
+
108
+ export function toolsOf(chat: { tools?: readonly FunctionTool[] }): ChatTool[] {
109
+ return (chat.tools ?? [])
110
+ .filter((t): t is { type: string; function: { name: string; description?: string; parameters?: unknown } } => t?.type === "function" && !!t.function?.name)
111
+ .map((t) => {
112
+ const schema = t.function.parameters ?? { type: "object", properties: {} }
113
+ return { name: t.function.name, description: t.function.description ?? "", schema, schemaText: JSON.stringify(schema) }
114
+ })
115
+ }
116
+
117
+ // catalog lists the caller's tools for the model. It sees MCP tools only
118
+ // through Cursor's GetDynamicTools and CallDynamicTool, and Cursor names
119
+ // them in a prompt of its own, which this conversation goes without:
120
+ // without the list the model says it has no such tool. Each entry is
121
+ // written as the CallDynamicTool call itself: listed as <tool name=...>,
122
+ // some models (GLM-5.3) called the names bare, as tools of their own, and
123
+ // those calls went nowhere (#11).
124
+ function catalog(tools: readonly ChatTool[]): string {
125
+ if (!tools.length) return ""
126
+ const visible = (value: unknown) => String(value ?? "").replaceAll("<", "\\u003c")
127
+ 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`
128
+ for (const t of tools) {
129
+ const name = JSON.stringify(String(t.name ?? "")).replaceAll("<", "\\u003c")
130
+ s += `<call>${CALL}({"namespace":"${NAMESPACE}","toolName":${name},"arguments":{...}})\n${visible(t.description)}\narguments schema: ${visible(t.schemaText)}\n</call>\n`
131
+ }
132
+ return s + "</dynamic_tool_catalog>"
133
+ }
134
+
135
+ // An OpenAI model's id is its call's and its item's, a line apart, which no
136
+ // caller would take as an id: callerID sends the line as __, and callID
137
+ // gives Cursor its own id back.
138
+ const callerID = (id: string) => id.replaceAll("\n", "__")
139
+ const callID = (id: string) => (id.startsWith("call_") ? id.replace("__fc_", "\nfc_") : id)
140
+
141
+ function result(id: string, text: string, isError: boolean) {
142
+ let res: unknown = text
143
+ try {
144
+ res = JSON.parse(text)
145
+ } catch {}
146
+ return {
147
+ type: "tool-result",
148
+ toolCallId: callID(id),
149
+ toolName: CALL,
150
+ result: res,
151
+ experimental_content: [{ type: "text", text }],
152
+ ...(isError ? { isError: true } : {}),
153
+ }
154
+ }
155
+
156
+ export function conversation(chat: { messages?: readonly unknown[] }, tools: readonly ChatTool[]): Conversation {
157
+ const messages = (chat.messages ?? []) as readonly ChatMessage[]
158
+ const out: Buffer[] = []
159
+ let size = 0
160
+ const add = (m: object) => out.push(Buffer.from(JSON.stringify(m)))
161
+ const system: string[] = []
162
+ let last = "."
163
+ for (const m of messages)
164
+ if (m.role === "system" || m.role === "developer") system.push(textOf(m.content))
165
+ const sys = system.filter(Boolean).join("\n\n") + catalog(tools)
166
+ size += sys.length
167
+ if (sys) add({ role: "system", content: sys })
168
+ let pending: string[] = []
169
+ let results: object[] = []
170
+ const answer = () => {
171
+ for (const id of pending) results.push(result(id, NO_RESULT, true))
172
+ pending = []
173
+ if (results.length) add({ role: "tool", content: results })
174
+ results = []
175
+ }
176
+ for (const m of joinSplitCalls(messages)) {
177
+ if (m.role === "system" || m.role === "developer") continue
178
+ if (m.role === "tool") {
179
+ const id = m.tool_call_id ?? ""
180
+ const i = pending.indexOf(id)
181
+ if (i >= 0) {
182
+ pending.splice(i, 1)
183
+ const text = textOf(m.content)
184
+ size += text.length
185
+ results.push(result(id, text, m.is_error === true || m.isError === true))
186
+ }
187
+ continue
188
+ }
189
+ if (m.role === "assistant") {
190
+ answer()
191
+ const content: object[] = []
192
+ const text = textOf(m.content)
193
+ if (text) content.push({ type: "text", text })
194
+ size += text.length
195
+ for (const c of m.tool_calls ?? []) {
196
+ if (c?.type && c.type !== "function") continue
197
+ const args = parseArgs(c.function?.arguments)
198
+ size += (c.function?.arguments ?? "").length + (c.function?.name ?? "").length
199
+ content.push({ type: "tool-call", toolCallId: callID(c.id), toolName: CALL, args: { namespace: NAMESPACE, toolName: c.function?.name, arguments: args } })
200
+ pending.push(c.id)
201
+ }
202
+ if (content.length) add({ role: "assistant", content })
203
+ continue
204
+ }
205
+ const content: object[] = []
206
+ const parts: readonly ChatPart[] = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content ?? []
207
+ let first = ""
208
+ for (const p of parts) {
209
+ if (p?.type === "text" && p.text) {
210
+ content.push({ type: "text", text: p.text })
211
+ size += p.text.length
212
+ first ||= p.text
213
+ } else if (p?.type === "image_url") {
214
+ const u = typeof p.image_url === "string" ? p.image_url : p.image_url?.url ?? ""
215
+ const d = /^data:([^;,]+);base64,(.*)$/s.exec(u)
216
+ if (d) content.push({ type: "image", mimeType: d[1], image: { __type: "Uint8Array", hex: Buffer.from(d[2], "base64").toString("hex") } })
217
+ else content.push({ type: "text", text: `[attachment image: ${u}]` })
218
+ } else if (p?.type === "file") {
219
+ content.push({ type: "text", text: `[attachment ${p.file?.filename ?? "file"}]` })
220
+ }
221
+ }
222
+ answer()
223
+ if (first) last = first
224
+ if (content.length) add({ role: "user", content })
225
+ }
226
+ answer()
227
+ for (const t of tools) size += t.name.length + t.description.length + t.schemaText.length
228
+ return { msgs: out, last, estimate: Math.floor(size / 4) }
229
+ }
230
+
231
+ function uuidOf(b: Buffer): string {
232
+ b = Buffer.from(b.subarray(0, 16))
233
+ b[6] = (b[6] & 0x0f) | 0x40
234
+ b[8] = (b[8] & 0x3f) | 0x80
235
+ const h = b.toString("hex")
236
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`
237
+ }
238
+
239
+ // conversationID is stable for one Pi session plus its first user message,
240
+ // so Cursor keeps sending the conversation to the machine that cached the
241
+ // prompt. The first message keeps subagents that share a session id apart.
242
+ // With no session it is "", and each Run gets a new id.
243
+ export function conversationID(chat: { messages?: readonly unknown[] } | undefined, session: string | undefined): string {
244
+ const key = String(session ?? "").trim()
245
+ if (!key) return ""
246
+ const msgs: readonly ChatMessage[] = Array.isArray(chat?.messages) ? chat.messages : []
247
+ const first = msgs.find((m) => m?.role === "user") ?? msgs[0]
248
+ // role and content only: a timestamp on the same first message must not move the id
249
+ const stable = first === undefined ? "" : JSON.stringify({ role: first.role, content: first.content })
250
+ const sum = createHash("sha256")
251
+ .update("cursor conversation\0" + key + "\0" + stable)
252
+ .digest()
253
+ return uuidOf(sum)
254
+ }
255
+
256
+ function toolDef(t: ExecTool): Buffer {
257
+ const d = pb().str(1, t.name)
258
+ if (t.description) d.str(2, t.description)
259
+ d.bytes(3, pbValue(t.schema))
260
+ return d.str(4, NAMESPACE).str(5, t.name).str(6, t.schemaText).done()
261
+ }
262
+
263
+ const env = () => pb().str(1, GOOS).str(2, tempDir()).str(10, "UTC")
264
+
265
+ export function buildRun(
266
+ msgs: readonly Buffer[],
267
+ lastUser: string,
268
+ tools: readonly ChatTool[],
269
+ model: string,
270
+ conv = "",
271
+ { maxMode = false, params = [] }: { maxMode?: boolean; params?: readonly ModelParam[] } = {},
272
+ ): { first: Buffer; blobs: BlobStore } {
273
+ const blobs: BlobStore = new Map()
274
+ const put = (b: Buffer) => {
275
+ const id = createHash("sha256").update(b).digest()
276
+ blobs.set(id.toString("hex"), b)
277
+ return id
278
+ }
279
+ const state = pb()
280
+ for (const m of msgs) state.bytes(1, put(m))
281
+ const mid = randomUUID()
282
+ const user = pb().str(1, lastUser).str(2, mid).varint(4, 1).done() // mode: agent
283
+ const turn = pb().bytes(1, pb().bytes(1, put(user)).str(10, mid)).done()
284
+ state.bytes(8, put(turn)).varint(10, 1).str(22, "cli")
285
+ const defs = tools.map(toolDef)
286
+ const rc = pb().bytes(4, env())
287
+ const mcp = pb()
288
+ for (const d of defs) {
289
+ rc.bytes(7, d)
290
+ mcp.bytes(1, d)
291
+ }
292
+ const action = pb().bytes(2, pb().bytes(2, rc)) // resume_action
293
+ // ModelDetails: model_id, display_model_id, display_name, max_mode (7);
294
+ // RequestedModel: model_id, max_mode (2), parameters (3)
295
+ const details = pb().str(1, model).str(3, model).str(4, model)
296
+ const requested = pb().str(1, model)
297
+ if (maxMode) {
298
+ details.varint(7, 1)
299
+ requested.varint(2, 1)
300
+ }
301
+ for (const p of params) requested.bytes(3, pb().str(1, p.id).str(2, p.value))
302
+ const rr = pb()
303
+ .bytes(1, state)
304
+ .bytes(2, action)
305
+ .bytes(3, details)
306
+ .bytes(4, mcp)
307
+ .str(5, conv || randomUUID())
308
+ .bytes(9, requested)
309
+ .varint(19, 1) // inline images
310
+ return { first: pb().bytes(1, rr).done(), blobs }
311
+ }
312
+
313
+ // usageOf is a TurnEndedUpdate as magpie counts usage, as the built-in's
314
+ // cursorUsage has it (magpie #498). Its input_tokens is the whole prompt,
315
+ // what was read from the cache and written to it included, as Cursor's
316
+ // own client has it (it takes both out to get the prompt's uncached
317
+ // rest); input is that rest, the cache added back for prompt_tokens. Its
318
+ // reasoning_tokens is kept as reasoning.
319
+ export function usageOf(uf: readonly Field[]): UsageCounts {
320
+ const [inp, cr, cw] = [pbNum(uf, 1), pbNum(uf, 3), pbNum(uf, 4)]
321
+ return { input: Math.max(inp - cr - cw, 0), output: pbNum(uf, 2), cacheRead: cr, cacheWrite: cw, reasoning: pbNum(uf, 5) }
322
+ }
323
+
324
+ export type DecodeOptions = {
325
+ send: (message: Buffer) => void
326
+ blobs: ReadonlyMap<string, Buffer>
327
+ tools: readonly ExecTool[]
328
+ estimate?: number
329
+ close?: () => void
330
+ /** The stateless step's own usage from the dashboard. false: none was counted. */
331
+ stepUsage?: () => Promise<UsageCounts | null | false>
332
+ /** What the conversation owes from earlier steps, sent on as magpie_deferred. */
333
+ owedUsage?: (final: boolean) => Promise<UsageCounts | null>
334
+ toolIdleMs?: number
335
+ }
336
+
337
+ type Next = { v: IteratorResult<Frame>; e?: undefined; idle?: undefined } | { e: unknown; v?: undefined; idle?: undefined } | { idle: true; v?: undefined; e?: undefined }
338
+
339
+ export async function* decode(
340
+ stream: Iterable<Frame> | AsyncIterable<Frame>,
341
+ { send, blobs, tools, estimate = 0, close, stepUsage, owedUsage, toolIdleMs = TOOL_IDLE_MS }: DecodeOptions,
342
+ ): AsyncGenerator<RunEvent, void> {
343
+ let calls = 0
344
+ let answered = 0
345
+ let ended = false
346
+ let listed = 0
347
+ const stepDone = () => {
348
+ if (!listed || calls + answered < listed) return false
349
+ if (calls > 0) return true
350
+ listed = 0
351
+ answered = 0
352
+ return false
353
+ }
354
+ let said = 0
355
+ let wrote = 0
356
+ let usage: UsageCounts = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 }
357
+ let counted = false
358
+ const finish = (more: UsageCounts | null) => {
359
+ if (!counted && !usage.output) usage.output = Math.floor((said + 3) / 4)
360
+ if (!counted && !usage.input && !usage.cacheRead && !usage.cacheWrite) usage.input = estimate
361
+ const prompt = usage.input + usage.cacheRead + usage.cacheWrite
362
+ const deferred = more && more.input + more.output + more.cacheRead + more.cacheWrite > 0
363
+ return {
364
+ stop: calls > 0 ? ("tool_calls" as const) : ("stop" as const),
365
+ usage: {
366
+ prompt_tokens: prompt,
367
+ completion_tokens: usage.output,
368
+ total_tokens: prompt + usage.output,
369
+ prompt_tokens_details: { cached_tokens: usage.cacheRead, cache_write_tokens: usage.cacheWrite },
370
+ ...(usage.reasoning ? { completion_tokens_details: { reasoning_tokens: usage.reasoning } } : {}),
371
+ ...(deferred
372
+ ? {
373
+ magpie_deferred: {
374
+ prompt_tokens: more.input + more.cacheRead + more.cacheWrite,
375
+ completion_tokens: more.output,
376
+ cached_tokens: more.cacheRead,
377
+ cache_write_tokens: more.cacheWrite,
378
+ },
379
+ }
380
+ : {}),
381
+ },
382
+ }
383
+ }
384
+ const settled = async () => {
385
+ if (calls > 0 && !ended && stepUsage) {
386
+ close?.()
387
+ const u = await stepUsage().catch(() => null)
388
+ if (u) usage = u
389
+ counted = u === false || !!u
390
+ } else if (calls > 0) {
391
+ close?.()
392
+ }
393
+ return finish(owedUsage ? await owedUsage(calls === 0).catch(() => null) : null)
394
+ }
395
+ const closeExec = (id: number) => send(pb().bytes(5, pb().bytes(1, pb().varint(1, id))).done())
396
+ async function* asAsync(src: Iterable<Frame> | AsyncIterable<Frame>) {
397
+ yield* src
398
+ }
399
+ const iter = asAsync(stream)[Symbol.asyncIterator]()
400
+ let idleTimer: ReturnType<typeof setTimeout> | undefined
401
+ const moreComing = () => calls > 0 && !(listed > 0 && calls + answered >= listed)
402
+ try {
403
+ while (true) {
404
+ const pending = iter.next().then((v): Next => ({ v }), (e): Next => ({ e }))
405
+ let got: Next
406
+ if (moreComing()) {
407
+ got = await Promise.race([
408
+ pending,
409
+ new Promise<Next>((resolve) => {
410
+ idleTimer = setTimeout(() => resolve({ idle: true }), toolIdleMs)
411
+ }),
412
+ ])
413
+ clearTimeout(idleTimer)
414
+ } else got = await pending
415
+ if (got.idle) {
416
+ yield await settled()
417
+ return
418
+ }
419
+ if (got.e) throw got.e
420
+ if (got.v!.done) {
421
+ if (calls > 0) yield await settled()
422
+ else yield { error: { status: 502, message: "the reply broke off: EOF" } }
423
+ return
424
+ }
425
+ const f = got.v!.value
426
+ if (f.end) {
427
+ const e = failure(200, f.data)
428
+ if (e.status < 200 || e.status > 299) yield { error: e }
429
+ else if (wrote === 0 && calls === 0) yield { error: { status: 502, message: "an empty reply" } }
430
+ else yield await settled()
431
+ return
432
+ }
433
+ for (const m of fields(f.data)) {
434
+ switch (m.num) {
435
+ case 1: // interaction_update
436
+ for (const u of fields(m.data)) {
437
+ const uf = fields(u.data)
438
+ switch (u.num) {
439
+ case 1: {
440
+ const t = pbStr(uf, 1)
441
+ if (t) {
442
+ wrote += t.length
443
+ said += t.length
444
+ yield { text: t }
445
+ }
446
+ break
447
+ }
448
+ case 4: {
449
+ const t = pbStr(uf, 1)
450
+ if (t) {
451
+ said += t.length
452
+ yield { reasoning: t }
453
+ }
454
+ break
455
+ }
456
+ case 14: // turn ended, with what it used
457
+ usage = usageOf(uf)
458
+ ended = true
459
+ counted = true
460
+ if (calls === 0) {
461
+ yield wrote === 0 ? { error: { status: 502, message: "an empty reply" } } : await settled()
462
+ return
463
+ }
464
+ yield await settled()
465
+ return
466
+ case 27: // how many tool calls the step makes
467
+ listed = pbNum(uf, 1)
468
+ if (stepDone()) {
469
+ yield await settled()
470
+ return
471
+ }
472
+ break
473
+ }
474
+ }
475
+ break
476
+ case 2: {
477
+ const call = exec(m.data, tools, send, closeExec)
478
+ if (call) {
479
+ said += (call.args ?? "").length
480
+ yield { tool: { index: calls++, ...call } }
481
+ } else if (!fields(m.data).some((e) => e.num === 10)) answered++
482
+ if (stepDone()) {
483
+ yield await settled()
484
+ return
485
+ }
486
+ break
487
+ }
488
+ case 4: {
489
+ const kv = fields(m.data)
490
+ const id = pbNum(kv, 1)
491
+ for (const k of kv) {
492
+ if (k.num === 2) {
493
+ const want = field(fields(k.data), 1)?.data.toString("hex") ?? ""
494
+ const b = blobs.get(want)
495
+ const res = b ? pb().bytes(1, b) : pb().bytes(2, pb().str(1, "blob not found"))
496
+ send(pb().bytes(3, pb().varint(1, id).bytes(2, res)).done())
497
+ } else if (k.num === 3) {
498
+ send(pb().bytes(3, pb().varint(1, id).bytes(3, EMPTY)).done())
499
+ }
500
+ }
501
+ break
502
+ }
503
+ }
504
+ }
505
+ }
506
+ } catch (caught) {
507
+ const e = caught as { message?: string } | null | undefined
508
+ if (calls > 0 && /EOF/.test(e?.message ?? "")) {
509
+ yield await settled()
510
+ return
511
+ }
512
+ yield { error: { status: 502, message: "the reply broke off: " + (e?.message ?? e) } }
513
+ } finally {
514
+ clearTimeout(idleTimer)
515
+ }
516
+ }
517
+
518
+ const NAMESPACES: readonly string[] = [NAMESPACE]
519
+ const bareName = (s: string) => {
520
+ for (const ns of NAMESPACES) if (s.startsWith(ns + "-")) return s.slice(ns.length + 1)
521
+ return s
522
+ }
523
+
524
+ export function exec(msg: Buffer, tools: readonly ExecTool[], send: (message: Buffer) => void, closeExec: (id: number) => void): ToolCall | null
525
+ export function exec(msg: Buffer, tools: readonly ExecTool[], send: (message: Buffer) => void, closeExec: (id: number) => void, native: true): NativeCall | null
526
+ export function exec(msg: Buffer, tools: readonly ExecTool[], send: (message: Buffer) => void, closeExec: (id: number) => void, native = false): ToolCall | NativeCall | null {
527
+ const es = native ? nativeFields(msg) : fields(msg)
528
+ if (native && es.some((e) => e.num === 1 && (e.wire !== 0 || !Number.isInteger(e.n) || e.n < 0 || e.n > 0xffffffff)))
529
+ throw new NativeSessionError(502, "invalid native exec request ID")
530
+ const id = pbNum(es, 1)
531
+ const execID = pbStr(es, 15)
532
+ let nativeCall: (Omit<NativeCall, "args"> & { args: object }) | undefined, nativeUnavailable = false
533
+ if (native) for (const e of es) if (e.num === 11) {
534
+ if (e.wire !== 2) throw new NativeSessionError(502, "invalid native MCP argument envelope")
535
+ const { fields: a, args } = nativeMcpArgs(e.data)
536
+ const name = pbStr(a, 5) || bareName(pbStr(a, 1))
537
+ const provider = pbStr(a, 4)
538
+ const server = pbStr(a, 9)
539
+ if (provider && !NAMESPACES.includes(provider) || server && !NAMESPACES.includes(server)) nativeUnavailable = true
540
+ if (pbNum(a, 7) || field(a, 6)) nativeUnavailable = true
541
+ if (!tools.some((t) => t.name === name)) nativeUnavailable = true
542
+ if (!pbStr(a, 5) && !NAMESPACES.some((ns) => pbStr(a, 1) === ns + "-" + name)) nativeUnavailable = true
543
+ const call = { requestID: id, execID, nativeID: pbStr(a, 3), name, args }
544
+ if (nativeCall && !isDeepStrictEqual(nativeCall, call)) throw new NativeSessionError(502, "ambiguous repeated native MCP argument envelopes")
545
+ nativeCall ??= call
546
+ }
547
+ const answer = (num: number, res: unknown) => {
548
+ send(pb().bytes(2, pb().varint(1, id).str(15, execID).bytes(num, res)).done())
549
+ closeExec(id)
550
+ }
551
+ const unavailable = () => {
552
+ send(pb().bytes(5, pb().bytes(2, pb().varint(1, id).str(2, "not available"))).done())
553
+ closeExec(id)
554
+ return null
555
+ }
556
+ if (nativeUnavailable) return unavailable()
557
+ for (const e of es) {
558
+ switch (e.num) {
559
+ case 11: {
560
+ // mcp_args: a call of the caller's tools
561
+ if (native) return { ...nativeCall!, args: JSON.stringify(nativeCall!.args) }
562
+ const a = fields(e.data)
563
+ const args: Record<string, unknown> = {}
564
+ for (const kv of a) {
565
+ if (kv.num !== 2) continue
566
+ const ef = fields(kv.data)
567
+ const v = field(ef, 2)
568
+ args[pbStr(ef, 1)] = v ? pbAny(v.data) : null
569
+ }
570
+ const name = pbStr(a, 5) || pbStr(a, 1).replace(/^pi-/, "")
571
+ const cid = callerID(pbStr(a, 3)) || "call_" + randomBytes(12).toString("hex")
572
+ if (!tools.some((t) => t.name === name)) {
573
+ send(pb().bytes(5, pb().bytes(2, pb().varint(1, id).str(2, "not available"))).done())
574
+ closeExec(id)
575
+ return null
576
+ }
577
+ return { id: cid, name, args: JSON.stringify(args) }
578
+ }
579
+ case 36: {
580
+ // mcp_state_exec_args: the tools there are
581
+ const srv = pb().str(1, NAMESPACE).str(2, NAMESPACE).str(7, "connected")
582
+ for (const t of tools) srv.bytes(5, toolDef(t))
583
+ answer(36, pb().bytes(1, pb().bytes(1, srv)))
584
+ return null
585
+ }
586
+ case 10: // request_context_args
587
+ answer(10, pb().bytes(1, pb().bytes(1, pb().bytes(4, env()))))
588
+ return null
589
+ }
590
+ }
591
+ // a shell, a file read or an edit of Cursor's own: never run
592
+ return unavailable()
593
+ }