mapigate 0.5.98 → 0.5.120

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.
Files changed (86) hide show
  1. package/README.md +7 -1
  2. package/dist/core/adapters/anthropic/streamAnthropicToOpenAi.js +94 -13
  3. package/dist/core/adapters/anthropic/types.js +3 -1
  4. package/dist/core/adapters/anthropicAdapter.js +2 -2
  5. package/dist/core/adapters/helpers/toolCallRescue.js +224 -10
  6. package/dist/core/adapters/responsesAdapter.js +56 -3
  7. package/dist/core/resilience/index.js +5 -0
  8. package/dist/core/router/earliestResetComparator.js +14 -4
  9. package/dist/core/router/loadBalancer.js +27 -3
  10. package/dist/core/scanner/modelScanner.js +8 -1
  11. package/dist/core/scanner/payloadExtractor.js +8 -3
  12. package/dist/core/scanner/urlResolver.js +10 -2
  13. package/dist/core/usage/quotaService.js +3 -1
  14. package/dist/providers/catalog/xiaomi-tokenplan/metadata.js +6 -1
  15. package/dist/providers/catalog/xiaomi-tokenplan/provider.js +71 -1
  16. package/dist/providers/core/base/baseProvider.js +1 -0
  17. package/dist/providers/runtime/antigravity/executor.js +1 -1
  18. package/dist/providers/runtime/antigravity/metadata.js +4 -3
  19. package/dist/providers/runtime/antigravity/provider.js +2 -2
  20. package/dist/providers/runtime/antigravity/quota.js +9 -3
  21. package/dist/providers/runtime/antigravity/routes.js +2 -2
  22. package/dist/providers/runtime/antigravity/types.js +10 -2
  23. package/dist/providers/runtime/antigravity/weekly.js +1 -1
  24. package/dist/providers/runtime/codex/models.js +1 -6
  25. package/dist/providers/runtime/codex/routes.js +40 -24
  26. package/dist/providers/runtime/cursor/cursorChecksum.js +80 -0
  27. package/dist/providers/runtime/cursor/cursorModels.js +194 -0
  28. package/dist/providers/runtime/cursor/cursorProtobuf.js +193 -0
  29. package/dist/providers/runtime/cursor/cursorSession.js +118 -0
  30. package/dist/providers/runtime/cursor/cursorStreamer.js +250 -0
  31. package/dist/providers/runtime/cursor/cursorWire.js +243 -0
  32. package/dist/providers/runtime/cursor/executor.js +129 -0
  33. package/dist/providers/runtime/cursor/index.js +6 -0
  34. package/dist/providers/runtime/cursor/provider.js +34 -10
  35. package/dist/providers/runtime/cursor-api/auth.js +47 -102
  36. package/dist/providers/runtime/cursor-api/metadata.js +4 -4
  37. package/dist/providers/runtime/cursor-api/provider.js +58 -21
  38. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  39. package/dist/providers/runtime/kiro/executor.js +4 -2
  40. package/dist/providers/runtime/kiro/metadata.js +2 -2
  41. package/dist/providers/runtime/mimo/metadata.js +1 -0
  42. package/dist/providers/runtime/mimo/provider.js +56 -0
  43. package/dist/server/index.js +10 -1
  44. package/dist/server/proxy/executorHelpers.js +12 -2
  45. package/dist/server/proxy/singleModelExecutor.js +2 -0
  46. package/dist/server/proxy/streaming/sseStreamer.js +7 -2
  47. package/dist/server/routes/apiModels.js +60 -0
  48. package/dist/server/routes/apiProviders.js +50 -9
  49. package/dist/server/routes/apiServer.js +110 -0
  50. package/dist/server/routes/apiSettings.js +35 -7
  51. package/dist/server/routes/apiUsage.js +5 -3
  52. package/dist/shared/constants/quotaOrder.js +1 -0
  53. package/dist/storage/database.js +31 -0
  54. package/dist/storage/repositories/accountModelRepo.js +108 -0
  55. package/dist/storage/repositories/logRepo.js +71 -10
  56. package/dist/storage/repositories/providerRepo.js +69 -59
  57. package/dist/storage/repositories/requestDetailsRepo.js +8 -0
  58. package/dist/storage/repositories/settingsRepo.js +17 -0
  59. package/dist/storage/repositories/usageRepo.js +228 -72
  60. package/dist/web/assets/{CliToolsTab-DE48Y4QZ.js → CliToolsTab-BzhczMaa.js} +1 -1
  61. package/dist/web/assets/{CombosTab-dsZhV95u.js → CombosTab-Cz8KYH4M.js} +1 -1
  62. package/dist/web/assets/{ConfirmModal-BTwfpfgO.js → ConfirmModal-BU1PPpF0.js} +1 -1
  63. package/dist/web/assets/{ConsoleLogTab-DtUTPoi7.js → ConsoleLogTab-CFvXde1l.js} +1 -1
  64. package/dist/web/assets/EditAccountModal-CS2TR4bt.js +1 -0
  65. package/dist/web/assets/{EndpointTab-Ya1KYJSp.js → EndpointTab-DZCRpAbh.js} +1 -1
  66. package/dist/web/assets/{MitmTab-Bl-E-IDY.js → MitmTab-CTfwqdey.js} +1 -1
  67. package/dist/web/assets/{ModelAutocompleteInput-COe36ge6.js → ModelAutocompleteInput-CAi2R2s9.js} +1 -1
  68. package/dist/web/assets/ProviderDetailPage-Dv2LpFj_.js +6 -0
  69. package/dist/web/assets/{ProvidersTab-COC-cJXg.js → ProvidersTab-DwHMHdPu.js} +1 -1
  70. package/dist/web/assets/QuotaTab-DS1y9gGp.js +1 -0
  71. package/dist/web/assets/SettingsTab-DULcs9O4.js +1 -0
  72. package/dist/web/assets/UsageTab-DKBaBAeT.js +1 -0
  73. package/dist/web/assets/index-BisuNW2y.css +1 -0
  74. package/dist/web/assets/index-DPdrZakW.js +2 -0
  75. package/dist/web/assets/metadataRegistry-7DDoxaR3.js +1 -0
  76. package/dist/web/assets/{providersData-DRVJJUB4.js → providersData-Br5RocnM.js} +1 -1
  77. package/dist/web/index.html +2 -2
  78. package/package.json +1 -1
  79. package/dist/web/assets/EditAccountModal-65P5phzh.js +0 -1
  80. package/dist/web/assets/ProviderDetailPage-BnQ7kK6s.js +0 -6
  81. package/dist/web/assets/QuotaTab-DkRBaW79.js +0 -1
  82. package/dist/web/assets/SettingsTab-DPcPmPUd.js +0 -1
  83. package/dist/web/assets/UsageTab-Danjts5j.js +0 -1
  84. package/dist/web/assets/index-CeC7GeyM.js +0 -2
  85. package/dist/web/assets/index-YgSWkEbZ.css +0 -1
  86. package/dist/web/assets/metadataRegistry-Dxrq24qH.js +0 -1
@@ -0,0 +1,250 @@
1
+ import crypto from "node:crypto";
2
+ import { decodeAgentFrames, decodeMessage, extractAgentString, agentMessage, createRequestContextResponse, rejectExecRequest, encodeKvClientMessage, decodeMcpArgs, } from "./cursorProtobuf.js";
3
+ import { visibleComposerContentFromThinking, } from "./cursorSession.js";
4
+ import { AnthropicAdapter } from "../../../core/adapters/anthropicAdapter.js";
5
+ import { createResponsesStreamState, openAiChunkToResponsesEvents, finalizeResponsesStream, } from "../../../core/adapters/responsesAdapter.js";
6
+ import { ResponseLogger } from "../../../server/proxy/responseLogger.js";
7
+ export function parseServerUpdates(serverMessage, session, composer, thinkingAcc, emitted, onEvent, finishTurn) {
8
+ if (serverMessage.has(1)) {
9
+ const update = decodeMessage(serverMessage.get(1)[0].value);
10
+ if (update.has(1)) {
11
+ const textDelta = extractAgentString(decodeMessage(update.get(1)[0].value), 1);
12
+ if (textDelta) {
13
+ emitted.text = true;
14
+ onEvent({ type: "text", value: textDelta });
15
+ }
16
+ }
17
+ if (update.has(4)) {
18
+ const thinkingDelta = extractAgentString(decodeMessage(update.get(4)[0].value), 1);
19
+ if (thinkingDelta) {
20
+ thinkingAcc.val += thinkingDelta;
21
+ if (composer) {
22
+ const visible = visibleComposerContentFromThinking(thinkingAcc.val);
23
+ if (visible.length > emitted.visible) {
24
+ const delta = visible.slice(emitted.visible);
25
+ emitted.visible = visible.length;
26
+ emitted.text = true;
27
+ onEvent({ type: "text", value: delta });
28
+ }
29
+ }
30
+ }
31
+ }
32
+ if (update.has(14))
33
+ finishTurn();
34
+ }
35
+ if (serverMessage.has(4)) {
36
+ const kv = decodeMessage(serverMessage.get(4)[0].value);
37
+ const kvId = kv.get(1)?.[0]?.value || 0;
38
+ const metadata = kv.get(4)?.[0]?.value || null;
39
+ if (kv.has(2)) {
40
+ session.write(encodeKvClientMessage(kvId, 2, agentMessage(1, new Uint8Array()), metadata));
41
+ }
42
+ else if (kv.has(3)) {
43
+ session.write(encodeKvClientMessage(kvId, 3, new Uint8Array(), metadata));
44
+ }
45
+ }
46
+ if (serverMessage.has(2)) {
47
+ const execRequest = decodeMessage(serverMessage.get(2)[0].value);
48
+ if (execRequest.has(10)) {
49
+ session.write(createRequestContextResponse(execRequest));
50
+ }
51
+ else if (execRequest.has(11)) {
52
+ const mcp = decodeMcpArgs(execRequest.get(11)[0].value);
53
+ const name = mcp.toolName || mcp.name;
54
+ if (name) {
55
+ onEvent({
56
+ type: "tool_call",
57
+ value: {
58
+ id: mcp.toolCallId || `call_${crypto.randomUUID()}`,
59
+ name,
60
+ arguments: JSON.stringify(mcp.args || {}),
61
+ },
62
+ });
63
+ onEvent({ type: "done", finishReason: "tool_calls" });
64
+ }
65
+ else {
66
+ onEvent({ type: "error", value: "Cursor AgentService requested an unsupported IDE tool" });
67
+ }
68
+ }
69
+ else {
70
+ const rejection = rejectExecRequest(execRequest);
71
+ if (rejection)
72
+ session.write(rejection);
73
+ else
74
+ onEvent({ type: "error", value: "Cursor AgentService requested an unsupported IDE tool" });
75
+ }
76
+ }
77
+ }
78
+ export async function runSessionLoop(session, composer, onEvent) {
79
+ let pending = Buffer.alloc(0);
80
+ let finished = false;
81
+ const thinkingAcc = { val: "" };
82
+ const emitted = { text: false, visible: 0 };
83
+ const finishTurn = () => {
84
+ if (!emitted.text && thinkingAcc.val) {
85
+ const fallback = composer ? visibleComposerContentFromThinking(thinkingAcc.val) : thinkingAcc.val.trim();
86
+ if (fallback) {
87
+ emitted.text = true;
88
+ onEvent({ type: "text", value: fallback });
89
+ }
90
+ }
91
+ finished = true;
92
+ if (emitted.text)
93
+ onEvent({ type: "done" });
94
+ else
95
+ onEvent({ type: "error", value: "Cursor AgentService returned an empty turn" });
96
+ };
97
+ try {
98
+ while (!finished) {
99
+ const { done, value } = await session.read();
100
+ if (done)
101
+ break;
102
+ pending = Buffer.concat([pending, Buffer.from(value)]);
103
+ pending = decodeAgentFrames(pending, (payload) => {
104
+ if (finished)
105
+ return;
106
+ const msg = decodeMessage(payload);
107
+ parseServerUpdates(msg, session, composer, thinkingAcc, emitted, onEvent, finishTurn);
108
+ });
109
+ }
110
+ if (!finished)
111
+ finishTurn();
112
+ }
113
+ finally {
114
+ try {
115
+ session.end();
116
+ }
117
+ catch { }
118
+ try {
119
+ session.close();
120
+ }
121
+ catch { }
122
+ }
123
+ return { sawContent: emitted.text };
124
+ }
125
+ export async function streamCursorSse(options) {
126
+ const { context, responseId, created, runWithRetry } = options;
127
+ const { res, clientFormat, requestId, targetModel, body } = context;
128
+ if (!res)
129
+ return { ok: false, status: 500, error: "Response writer unavailable" };
130
+ res.setHeader("Content-Type", "text/event-stream");
131
+ res.setHeader("Cache-Control", "no-cache");
132
+ res.setHeader("Connection", "keep-alive");
133
+ res.setHeader("X-Accel-Buffering", "no");
134
+ res.flushHeaders?.();
135
+ const anthropicState = clientFormat === "anthropic" ? AnthropicAdapter.createStreamState(`msg_${requestId}`, body.tools) : undefined;
136
+ const responsesState = clientFormat === "responses" ? createResponsesStreamState(requestId) : undefined;
137
+ const emit = (obj) => {
138
+ if (clientFormat === "responses" && responsesState) {
139
+ const events = openAiChunkToResponsesEvents(obj, responsesState);
140
+ for (const ev of events)
141
+ res.write(`event: ${ev.event}\ndata: ${JSON.stringify(ev.data)}\n\n`);
142
+ }
143
+ else if (clientFormat === "anthropic" && anthropicState) {
144
+ const events = AnthropicAdapter.openAiChunkToAnthropicEvent(obj, `msg_${requestId}`, anthropicState);
145
+ for (const ev of events)
146
+ res.write(ev);
147
+ }
148
+ else {
149
+ res.write(`data: ${JSON.stringify(obj)}\n\n`);
150
+ }
151
+ };
152
+ if (clientFormat === "anthropic") {
153
+ res.write(`event: message_start\ndata: ${JSON.stringify({
154
+ type: "message_start",
155
+ message: { id: `msg_${requestId}`, type: "message", role: "assistant", model: targetModel, content: [] },
156
+ })}\n\n`);
157
+ }
158
+ emit({
159
+ id: responseId,
160
+ object: "chat.completion.chunk",
161
+ created,
162
+ model: targetModel,
163
+ choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
164
+ });
165
+ let fullStreamText = "";
166
+ await runWithRetry((ev) => {
167
+ if (ev.type === "text") {
168
+ fullStreamText += ev.value;
169
+ emit({
170
+ id: responseId,
171
+ object: "chat.completion.chunk",
172
+ created,
173
+ model: targetModel,
174
+ choices: [{ index: 0, delta: { content: ev.value }, finish_reason: null }],
175
+ });
176
+ }
177
+ else if (ev.type === "thinking") {
178
+ emit({
179
+ id: responseId,
180
+ object: "chat.completion.chunk",
181
+ created,
182
+ model: targetModel,
183
+ choices: [{ index: 0, delta: { reasoning_content: ev.value }, finish_reason: null }],
184
+ });
185
+ }
186
+ else if (ev.type === "tool_call") {
187
+ emit({
188
+ id: responseId,
189
+ object: "chat.completion.chunk",
190
+ created,
191
+ model: targetModel,
192
+ choices: [{
193
+ index: 0,
194
+ delta: {
195
+ tool_calls: [{
196
+ index: 0,
197
+ id: ev.value.id,
198
+ type: "function",
199
+ function: { name: ev.value.name, arguments: ev.value.arguments },
200
+ }],
201
+ },
202
+ finish_reason: null,
203
+ }],
204
+ });
205
+ }
206
+ else if (ev.type === "error") {
207
+ res.write(`data: ${JSON.stringify({ error: { message: ev.value, type: "api_error" } })}\n\n`);
208
+ }
209
+ else if (ev.type === "done") {
210
+ emit({
211
+ id: responseId,
212
+ object: "chat.completion.chunk",
213
+ created,
214
+ model: targetModel,
215
+ choices: [{ index: 0, delta: {}, finish_reason: ev.finishReason || "stop" }],
216
+ });
217
+ }
218
+ });
219
+ if (clientFormat === "responses" && responsesState) {
220
+ const finalEvents = finalizeResponsesStream(responsesState);
221
+ for (const ev of finalEvents)
222
+ res.write(`event: ${ev.event}\ndata: ${JSON.stringify(ev.data)}\n\n`);
223
+ res.write("data: [DONE]\n\n");
224
+ }
225
+ else if (clientFormat === "anthropic" && anthropicState) {
226
+ const finalEvents = AnthropicAdapter.finalizeStream(anthropicState);
227
+ for (const ev of finalEvents)
228
+ res.write(ev);
229
+ }
230
+ else {
231
+ res.write("data: [DONE]\n\n");
232
+ }
233
+ res.end();
234
+ const durationMs = Date.now() - context.startTime;
235
+ const completionTokens = Math.ceil(fullStreamText.length / 4);
236
+ const promptTokens = context.rtkStats?.compressedTokens || 0;
237
+ ResponseLogger.logSuccess({
238
+ requestId: context.requestId, startTime: context.startTime, durationMs,
239
+ clientTool: context.clientTool || "generic",
240
+ rawModel: context.rawModel || targetModel, targetModel, providerId: "cursor",
241
+ accountId: context.account?.id, accountName: context.account?.name,
242
+ apiKeyId: context.apiKeyId, apiKeyName: context.apiKeyName,
243
+ promptTokens, completionTokens, cachedTokens: 0, cacheCreationTokens: 0, reasoningTokens: 0,
244
+ tokensSavedByRtk: context.rtkStats?.tokensSaved || 0, is1mContext: context.is1mContext,
245
+ requestHeaders: context.req?.headers || {},
246
+ requestBody: context.req?.body || body,
247
+ clientResponse: { status: 200, headers: { "content-type": "text/event-stream" }, body: { text: "Stream completed" } },
248
+ });
249
+ return { ok: true, status: 200, modelUsed: targetModel, isStream: true };
250
+ }
@@ -0,0 +1,243 @@
1
+ import zlib from "node:zlib";
2
+ export const WIRE_TYPE = {
3
+ VARINT: 0,
4
+ FIXED64: 1,
5
+ LEN: 2,
6
+ FIXED32: 5,
7
+ };
8
+ export const COMPRESS_FLAG = {
9
+ NONE: 0x00,
10
+ GZIP: 0x01,
11
+ TRAILER: 0x02,
12
+ GZIP_TRAILER: 0x03,
13
+ };
14
+ export function concatBuffers(...parts) {
15
+ const length = parts.reduce((total, part) => total + part.length, 0);
16
+ const result = new Uint8Array(length);
17
+ let offset = 0;
18
+ for (const part of parts) {
19
+ result.set(part, offset);
20
+ offset += part.length;
21
+ }
22
+ return result;
23
+ }
24
+ export function encodeVarint(value) {
25
+ const bytes = [];
26
+ let v = value;
27
+ while (v >= 0x80) {
28
+ bytes.push((v & 0x7f) | 0x80);
29
+ v >>>= 7;
30
+ }
31
+ bytes.push(v & 0x7f);
32
+ return new Uint8Array(bytes);
33
+ }
34
+ export function decodeVarint(buffer, offset) {
35
+ let result = 0;
36
+ let shift = 0;
37
+ let pos = offset;
38
+ while (pos < buffer.length) {
39
+ const b = buffer[pos];
40
+ result |= (b & 0x7f) << shift;
41
+ pos++;
42
+ if (!(b & 0x80))
43
+ break;
44
+ shift += 7;
45
+ }
46
+ return [result, pos];
47
+ }
48
+ export function encodeField(fieldNum, wireType, value) {
49
+ const tag = (fieldNum << 3) | wireType;
50
+ const tagBytes = encodeVarint(tag);
51
+ if (wireType === WIRE_TYPE.VARINT) {
52
+ const num = typeof value === "boolean" ? (value ? 1 : 0) : Number(value);
53
+ return concatBuffers(tagBytes, encodeVarint(num));
54
+ }
55
+ if (wireType === WIRE_TYPE.LEN) {
56
+ let dataBytes;
57
+ if (typeof value === "string") {
58
+ dataBytes = new TextEncoder().encode(value);
59
+ }
60
+ else if (value instanceof Uint8Array) {
61
+ dataBytes = value;
62
+ }
63
+ else if (Buffer.isBuffer(value)) {
64
+ dataBytes = new Uint8Array(value);
65
+ }
66
+ else {
67
+ dataBytes = new Uint8Array(0);
68
+ }
69
+ const lengthBytes = encodeVarint(dataBytes.length);
70
+ return concatBuffers(tagBytes, lengthBytes, dataBytes);
71
+ }
72
+ if (wireType === WIRE_TYPE.FIXED64) {
73
+ const buf = Buffer.alloc(8);
74
+ buf.writeDoubleLE(Number(value));
75
+ return concatBuffers(tagBytes, buf);
76
+ }
77
+ return new Uint8Array(0);
78
+ }
79
+ export function decodeField(buffer, offset) {
80
+ if (offset >= buffer.length)
81
+ return [null, null, null, offset];
82
+ const [tag, pos1] = decodeVarint(buffer, offset);
83
+ const fieldNum = tag >> 3;
84
+ const wireType = tag & 0x07;
85
+ let value;
86
+ let pos = pos1;
87
+ if (wireType === WIRE_TYPE.VARINT) {
88
+ [value, pos] = decodeVarint(buffer, pos);
89
+ }
90
+ else if (wireType === WIRE_TYPE.LEN) {
91
+ const [length, pos2] = decodeVarint(buffer, pos);
92
+ value = buffer.subarray(pos2, pos2 + length);
93
+ pos = pos2 + length;
94
+ }
95
+ else if (wireType === WIRE_TYPE.FIXED64) {
96
+ value = buffer.subarray(pos, pos + 8);
97
+ pos += 8;
98
+ }
99
+ else if (wireType === WIRE_TYPE.FIXED32) {
100
+ value = buffer.subarray(pos, pos + 4);
101
+ pos += 4;
102
+ }
103
+ else {
104
+ value = null;
105
+ }
106
+ return [fieldNum, wireType, value, pos];
107
+ }
108
+ export function decodeMessage(data) {
109
+ const fields = new Map();
110
+ let pos = 0;
111
+ while (pos < data.length) {
112
+ const [fieldNum, wireType, value, newPos] = decodeField(data, pos);
113
+ if (fieldNum === null || wireType === null)
114
+ break;
115
+ let arr = fields.get(fieldNum);
116
+ if (!arr) {
117
+ arr = [];
118
+ fields.set(fieldNum, arr);
119
+ }
120
+ arr.push({ wireType, value });
121
+ pos = newPos;
122
+ }
123
+ return fields;
124
+ }
125
+ export function wrapConnectRPCFrame(payload, compress = false) {
126
+ let finalPayload = payload;
127
+ let flags = 0x00;
128
+ if (compress) {
129
+ finalPayload = new Uint8Array(zlib.gzipSync(Buffer.from(payload)));
130
+ flags = 0x01;
131
+ }
132
+ const frame = new Uint8Array(5 + finalPayload.length);
133
+ frame[0] = flags;
134
+ frame[1] = (finalPayload.length >> 24) & 0xff;
135
+ frame[2] = (finalPayload.length >> 16) & 0xff;
136
+ frame[3] = (finalPayload.length >> 8) & 0xff;
137
+ frame[4] = finalPayload.length & 0xff;
138
+ frame.set(finalPayload, 5);
139
+ return frame;
140
+ }
141
+ export function parseConnectRPCFrame(buffer) {
142
+ if (buffer.length < 5)
143
+ return null;
144
+ const flags = buffer[0];
145
+ const length = (buffer[1] << 24) | (buffer[2] << 16) | (buffer[3] << 8) | buffer[4];
146
+ if (buffer.length < 5 + length)
147
+ return null;
148
+ let payload = buffer.subarray(5, 5 + length);
149
+ if (flags === 0x01) {
150
+ try {
151
+ payload = new Uint8Array(zlib.gunzipSync(Buffer.from(payload)));
152
+ }
153
+ catch { }
154
+ }
155
+ return { flags, length, payload, consumed: 5 + length };
156
+ }
157
+ export function decodeAgentFrames(buffer, onFrame) {
158
+ let pending = Buffer.from(buffer || []);
159
+ while (pending.length >= 5) {
160
+ const flags = pending[0];
161
+ const length = pending.readUInt32BE(1);
162
+ if (pending.length < 5 + length)
163
+ break;
164
+ let payload = pending.subarray(5, 5 + length);
165
+ pending = pending.subarray(5 + length);
166
+ if (flags & COMPRESS_FLAG.GZIP) {
167
+ try {
168
+ payload = zlib.gunzipSync(payload);
169
+ }
170
+ catch { }
171
+ }
172
+ if (!(flags & COMPRESS_FLAG.TRAILER))
173
+ onFrame(payload);
174
+ }
175
+ return pending;
176
+ }
177
+ export const agentString = (field, value) => encodeField(field, WIRE_TYPE.LEN, value);
178
+ export const agentMessage = (field, value) => encodeField(field, WIRE_TYPE.LEN, value);
179
+ export const agentBool = (field, value) => encodeField(field, WIRE_TYPE.VARINT, value ? 1 : 0);
180
+ export function extractAgentString(message, field) {
181
+ const value = message?.get(field)?.[0]?.value;
182
+ return value ? Buffer.from(value).toString("utf8") : "";
183
+ }
184
+ // google.protobuf.Value encoding and decoding
185
+ const PB_VALUE = { NULL: 1, NUMBER: 2, STRING: 3, BOOL: 4, STRUCT: 5, LIST: 6 };
186
+ const PB_STRUCT_FIELDS = 1;
187
+ const PB_MAP_KEY = 1;
188
+ const PB_MAP_VALUE = 2;
189
+ const PB_LIST_VALUES = 1;
190
+ export function encodeAgentValue(value) {
191
+ if (value === null || value === undefined) {
192
+ return encodeField(PB_VALUE.NULL, WIRE_TYPE.VARINT, 0);
193
+ }
194
+ if (typeof value === "boolean") {
195
+ return encodeField(PB_VALUE.BOOL, WIRE_TYPE.VARINT, value ? 1 : 0);
196
+ }
197
+ if (typeof value === "number") {
198
+ return encodeField(PB_VALUE.NUMBER, WIRE_TYPE.FIXED64, value);
199
+ }
200
+ if (typeof value === "string") {
201
+ return encodeField(PB_VALUE.STRING, WIRE_TYPE.LEN, value);
202
+ }
203
+ if (Array.isArray(value)) {
204
+ const items = value.map((item) => encodeField(PB_LIST_VALUES, WIRE_TYPE.LEN, encodeAgentValue(item)));
205
+ return encodeField(PB_VALUE.LIST, WIRE_TYPE.LEN, concatBuffers(...items));
206
+ }
207
+ if (typeof value === "object") {
208
+ const entries = Object.entries(value).map(([key, val]) => encodeField(PB_STRUCT_FIELDS, WIRE_TYPE.LEN, concatBuffers(encodeField(PB_MAP_KEY, WIRE_TYPE.LEN, key), encodeField(PB_MAP_VALUE, WIRE_TYPE.LEN, encodeAgentValue(val)))));
209
+ return encodeField(PB_VALUE.STRUCT, WIRE_TYPE.LEN, concatBuffers(...entries));
210
+ }
211
+ return encodeField(PB_VALUE.STRING, WIRE_TYPE.LEN, String(value));
212
+ }
213
+ export function decodeAgentValue(bytes) {
214
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
215
+ const fields = decodeMessage(buf);
216
+ if (fields.has(PB_VALUE.NULL))
217
+ return null;
218
+ if (fields.has(PB_VALUE.BOOL))
219
+ return fields.get(PB_VALUE.BOOL)[0].value !== 0;
220
+ if (fields.has(PB_VALUE.NUMBER)) {
221
+ const raw = Buffer.from(fields.get(PB_VALUE.NUMBER)[0].value);
222
+ return raw.readDoubleLE(0);
223
+ }
224
+ if (fields.has(PB_VALUE.STRING)) {
225
+ return Buffer.from(fields.get(PB_VALUE.STRING)[0].value).toString("utf8");
226
+ }
227
+ if (fields.has(PB_VALUE.STRUCT)) {
228
+ const result = {};
229
+ for (const entry of decodeMessage(Buffer.from(fields.get(PB_VALUE.STRUCT)[0].value)).get(PB_STRUCT_FIELDS) || []) {
230
+ const pair = decodeMessage(Buffer.from(entry.value));
231
+ const keyBuf = pair.get(PB_MAP_KEY)?.[0]?.value;
232
+ const key = keyBuf ? Buffer.from(keyBuf).toString("utf8") : "";
233
+ if (key) {
234
+ result[key] = decodeAgentValue(pair.get(PB_MAP_VALUE)?.[0]?.value);
235
+ }
236
+ }
237
+ return result;
238
+ }
239
+ if (fields.has(PB_VALUE.LIST)) {
240
+ return (decodeMessage(Buffer.from(fields.get(PB_VALUE.LIST)[0].value)).get(PB_LIST_VALUES) || []).map((item) => decodeAgentValue(item.value));
241
+ }
242
+ return null;
243
+ }
@@ -0,0 +1,129 @@
1
+ import { buildCursorHeaders } from "./cursorChecksum.js";
2
+ import { buildAgentRunFrame, tailOnlyCursorMessages } from "./cursorProtobuf.js";
3
+ import { resolveCursorModels, resolveAutoModelSelection } from "./cursorModels.js";
4
+ import { AGENT_RUN_URL, TAIL_ONLY_THRESHOLD, isComposerModel, openAgentHttp2Stream, } from "./cursorSession.js";
5
+ import { runSessionLoop, streamCursorSse, } from "./cursorStreamer.js";
6
+ export async function executeCursor(context) {
7
+ const { body, targetModel, isPanel, res } = context;
8
+ const isStreaming = body.stream !== false && !isPanel;
9
+ const rawToken = context.account?.rawApiKey || context.account?.apiKey || "";
10
+ const psd = (context.account?.providerSpecificData || {});
11
+ const cleanToken = rawToken.includes("::") ? rawToken.split("::")[1] : rawToken;
12
+ const machineId = psd.machineId || null;
13
+ if (!cleanToken) {
14
+ return { ok: false, status: 401, error: "Cursor access token is required" };
15
+ }
16
+ const headers = buildCursorHeaders(cleanToken, machineId, psd.ghostMode !== false);
17
+ const originalMessages = body.messages || [];
18
+ let workingMessages = originalMessages;
19
+ const tools = body.tools || [];
20
+ let runModel = targetModel;
21
+ if (targetModel === "default" || targetModel === "auto") {
22
+ const catalog = await resolveCursorModels({ accessToken: cleanToken, machineId: machineId || undefined });
23
+ const selection = resolveAutoModelSelection(catalog?.models || []);
24
+ if (selection)
25
+ runModel = selection.modelId;
26
+ }
27
+ const openSession = (msgs) => {
28
+ const sess = openAgentHttp2Stream(AGENT_RUN_URL, headers, context.abortController?.signal);
29
+ sess.write(buildAgentRunFrame(msgs, runModel, tools, body.reasoning_effort || body.reasoning?.effort));
30
+ return sess;
31
+ };
32
+ let session;
33
+ try {
34
+ session = openSession(workingMessages);
35
+ }
36
+ catch (err) {
37
+ return { ok: false, status: 500, error: `Cursor AgentService connection error: ${err.message}` };
38
+ }
39
+ const responseHeaders = await session.responseHeaders.catch((err) => {
40
+ session.close();
41
+ throw err;
42
+ });
43
+ const status = Number(responseHeaders[":status"] || 0);
44
+ if (status !== 200) {
45
+ let errorText = "";
46
+ try {
47
+ while (true) {
48
+ const { done, value } = await session.read();
49
+ if (done)
50
+ break;
51
+ errorText += Buffer.from(value || []).toString("utf8");
52
+ }
53
+ }
54
+ catch { }
55
+ session.close();
56
+ return { ok: false, status: status || 500, error: `Cursor AgentService returned ${status}: ${errorText || "Request failed"}` };
57
+ }
58
+ const responseId = `chatcmpl-msg_${Date.now()}`;
59
+ const created = Math.floor(Date.now() / 1000);
60
+ const composer = isComposerModel(runModel);
61
+ const runWithRetry = async (onEvent) => {
62
+ let outputStarted = false;
63
+ const wrapped = (ev) => {
64
+ if (ev.type === "text" || ev.type === "thinking" || ev.type === "tool_call")
65
+ outputStarted = true;
66
+ onEvent(ev);
67
+ };
68
+ let turnError = null;
69
+ const result = await runSessionLoop(session, composer, (ev) => {
70
+ if (ev.type === "error")
71
+ turnError = ev;
72
+ else
73
+ wrapped(ev);
74
+ });
75
+ if (turnError && originalMessages.length >= TAIL_ONLY_THRESHOLD && !outputStarted && !context.abortController?.signal?.aborted) {
76
+ workingMessages = tailOnlyCursorMessages(originalMessages);
77
+ session = openSession(workingMessages);
78
+ const retryHdrs = await session.responseHeaders;
79
+ if (Number(retryHdrs[":status"] || 0) === 200) {
80
+ return runSessionLoop(session, composer, wrapped);
81
+ }
82
+ }
83
+ if (turnError)
84
+ wrapped(turnError);
85
+ return result;
86
+ };
87
+ if (!isStreaming || !res) {
88
+ let fullText = "";
89
+ let reasoning = "";
90
+ let agentError = null;
91
+ const toolCalls = [];
92
+ let finishReason = "stop";
93
+ await runWithRetry((ev) => {
94
+ if (ev.type === "text")
95
+ fullText += ev.value;
96
+ else if (ev.type === "thinking")
97
+ reasoning += ev.value;
98
+ else if (ev.type === "tool_call") {
99
+ toolCalls.push({ id: ev.value.id, type: "function", function: { name: ev.value.name, arguments: ev.value.arguments } });
100
+ finishReason = "tool_calls";
101
+ }
102
+ else if (ev.type === "error")
103
+ agentError = ev.value;
104
+ else if (ev.type === "done" && ev.finishReason)
105
+ finishReason = ev.finishReason;
106
+ });
107
+ if (agentError)
108
+ return { ok: false, status: 400, error: agentError };
109
+ const message = {
110
+ role: "assistant",
111
+ content: fullText || null,
112
+ ...(reasoning ? { reasoning_content: reasoning } : {}),
113
+ ...(toolCalls.length ? { tool_calls: toolCalls } : {}),
114
+ };
115
+ return {
116
+ ok: true,
117
+ status: 200,
118
+ modelUsed: targetModel,
119
+ json: {
120
+ id: responseId,
121
+ object: "chat.completion",
122
+ created,
123
+ model: targetModel,
124
+ choices: [{ index: 0, message, finish_reason: finishReason }],
125
+ },
126
+ };
127
+ }
128
+ return streamCursorSse({ context, responseId, created, runWithRetry });
129
+ }
@@ -1,3 +1,9 @@
1
1
  export * from "./metadata.js";
2
2
  export * from "./provider.js";
3
3
  export * from "./routes.js";
4
+ export * from "./cursorChecksum.js";
5
+ export * from "./cursorWire.js";
6
+ export * from "./cursorProtobuf.js";
7
+ export * from "./cursorModels.js";
8
+ export * from "./cursorStreamer.js";
9
+ export * from "./executor.js";
@@ -1,25 +1,49 @@
1
1
  import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
2
2
  import { metadata } from "./metadata.js";
3
+ import { executeCursor } from "./executor.js";
4
+ import { fetchCursorCatalog } from "./cursorModels.js";
3
5
  export class CursorProvider extends OpenAiCompatibleProvider {
4
6
  id = metadata.id;
5
7
  name = metadata.name;
6
8
  defaultFormat = metadata.format || "openai";
9
+ async execute(context, _dispatchSingleModel) {
10
+ return executeCursor(context);
11
+ }
7
12
  async probeModels(context) {
8
- const token = (context.account?.rawApiKey || context.apiKey || "").trim();
9
- if (!token) {
13
+ const rawToken = (context.account?.rawApiKey || context.apiKey || "").trim();
14
+ if (!rawToken) {
10
15
  return {
11
16
  success: false,
12
17
  error: "Cursor access token is required (import from Cursor IDE or provide token).",
13
18
  };
14
19
  }
15
- // Cursor uses connect+proto on api2.cursor.sh and requires machine ID.
16
- // Presence of non-empty access token means connection is active.
17
- return {
18
- success: true,
19
- endpointUrl: "https://api2.cursor.sh",
20
- models: metadata.models.map((m) => ({ id: m.id, name: m.name, contextLength: m.contextLength })),
21
- count: metadata.models.length,
22
- };
20
+ const cleanToken = rawToken.includes("::") ? rawToken.split("::")[1] : rawToken;
21
+ const psd = (context.account?.providerSpecificData || context.providerSpecificData || {});
22
+ const machineId = psd.machineId || undefined;
23
+ const timeoutMs = context.timeoutMs || 10_000;
24
+ try {
25
+ const catalog = await fetchCursorCatalog({ accessToken: cleanToken, machineId }, undefined, timeoutMs);
26
+ const models = catalog.map((m) => ({
27
+ id: m.id,
28
+ name: m.name || m.id,
29
+ contextLength: 128000,
30
+ }));
31
+ return {
32
+ success: true,
33
+ endpointUrl: "https://agent.api5.cursor.sh",
34
+ models: models.length ? models : metadata.models.map((m) => ({ id: m.id, name: m.name, contextLength: m.contextLength })),
35
+ count: models.length || metadata.models.length,
36
+ };
37
+ }
38
+ catch (err) {
39
+ const status = err?.status;
40
+ const isAuthError = status === 401 || status === 403;
41
+ return {
42
+ success: false,
43
+ error: `Cursor live probing failed: ${err.message || String(err)}`,
44
+ authError: isAuthError ? `Authentication failed (HTTP ${status}): Invalid or expired Cursor access token` : undefined,
45
+ };
46
+ }
23
47
  }
24
48
  }
25
49
  export default CursorProvider;