mapigate 0.5.98 → 0.5.123

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 (93) 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/mitm/handlers/base.js +58 -18
  15. package/dist/mitm/manager.js +5 -1
  16. package/dist/providers/catalog/xiaomi-tokenplan/metadata.js +6 -1
  17. package/dist/providers/catalog/xiaomi-tokenplan/provider.js +71 -1
  18. package/dist/providers/core/base/baseProvider.js +1 -0
  19. package/dist/providers/runtime/antigravity/executor.js +1 -1
  20. package/dist/providers/runtime/antigravity/metadata.js +4 -3
  21. package/dist/providers/runtime/antigravity/provider.js +2 -2
  22. package/dist/providers/runtime/antigravity/quota.js +9 -3
  23. package/dist/providers/runtime/antigravity/routes.js +2 -2
  24. package/dist/providers/runtime/antigravity/types.js +10 -2
  25. package/dist/providers/runtime/antigravity/weekly.js +1 -1
  26. package/dist/providers/runtime/codex/models.js +1 -6
  27. package/dist/providers/runtime/codex/routes.js +40 -24
  28. package/dist/providers/runtime/cursor/cursorChecksum.js +80 -0
  29. package/dist/providers/runtime/cursor/cursorModels.js +194 -0
  30. package/dist/providers/runtime/cursor/cursorProtobuf.js +193 -0
  31. package/dist/providers/runtime/cursor/cursorSession.js +118 -0
  32. package/dist/providers/runtime/cursor/cursorStreamer.js +250 -0
  33. package/dist/providers/runtime/cursor/cursorWire.js +243 -0
  34. package/dist/providers/runtime/cursor/executor.js +129 -0
  35. package/dist/providers/runtime/cursor/index.js +6 -0
  36. package/dist/providers/runtime/cursor/provider.js +34 -10
  37. package/dist/providers/runtime/cursor-api/auth.js +47 -102
  38. package/dist/providers/runtime/cursor-api/metadata.js +4 -4
  39. package/dist/providers/runtime/cursor-api/provider.js +58 -21
  40. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  41. package/dist/providers/runtime/kiro/executor.js +4 -2
  42. package/dist/providers/runtime/kiro/metadata.js +2 -2
  43. package/dist/providers/runtime/mimo/metadata.js +1 -0
  44. package/dist/providers/runtime/mimo/provider.js +56 -0
  45. package/dist/server/index.js +10 -1
  46. package/dist/server/proxy/executorHelpers.js +12 -2
  47. package/dist/server/proxy/singleModelExecutor.js +2 -0
  48. package/dist/server/proxy/streaming/sseStreamer.js +7 -2
  49. package/dist/server/routes/apiMitm.js +50 -0
  50. package/dist/server/routes/apiModels.js +60 -0
  51. package/dist/server/routes/apiProviders.js +50 -9
  52. package/dist/server/routes/apiServer.js +110 -0
  53. package/dist/server/routes/apiSettings.js +35 -7
  54. package/dist/server/routes/apiUsage.js +5 -3
  55. package/dist/server/routes/mitmRouterTargetHelper.js +109 -0
  56. package/dist/shared/constants/quotaOrder.js +1 -0
  57. package/dist/storage/database.js +31 -0
  58. package/dist/storage/repositories/accountModelRepo.js +108 -0
  59. package/dist/storage/repositories/logRepo.js +71 -10
  60. package/dist/storage/repositories/mitmRepo.js +44 -0
  61. package/dist/storage/repositories/providerRepo.js +69 -59
  62. package/dist/storage/repositories/requestDetailsRepo.js +8 -0
  63. package/dist/storage/repositories/settingsRepo.js +17 -0
  64. package/dist/storage/repositories/usageRepo.js +228 -72
  65. package/dist/web/assets/{CliToolsTab-DE48Y4QZ.js → CliToolsTab-D-0zU55K.js} +1 -1
  66. package/dist/web/assets/{CombosTab-dsZhV95u.js → CombosTab-V_ldcQni.js} +1 -1
  67. package/dist/web/assets/{ConfirmModal-BTwfpfgO.js → ConfirmModal-B7vVauYn.js} +1 -1
  68. package/dist/web/assets/{ConsoleLogTab-DtUTPoi7.js → ConsoleLogTab-Byt7Fr4V.js} +1 -1
  69. package/dist/web/assets/EditAccountModal-p6rlIU5X.js +1 -0
  70. package/dist/web/assets/{EndpointTab-Ya1KYJSp.js → EndpointTab-BHYn9Syj.js} +1 -1
  71. package/dist/web/assets/MitmTab-sRzVrlgW.js +14 -0
  72. package/dist/web/assets/ModelAutocompleteInput-ClwXyzE7.js +1 -0
  73. package/dist/web/assets/ProviderDetailPage-DgClsBMU.js +6 -0
  74. package/dist/web/assets/{ProvidersTab-COC-cJXg.js → ProvidersTab-CPMTBmXq.js} +1 -1
  75. package/dist/web/assets/QuotaTab-NaCPxtWq.js +1 -0
  76. package/dist/web/assets/SettingsTab-BUKXj5iT.js +1 -0
  77. package/dist/web/assets/UsageTab-BDTnu1v_.js +1 -0
  78. package/dist/web/assets/index-BdD7LHGu.js +2 -0
  79. package/dist/web/assets/index-BisuNW2y.css +1 -0
  80. package/dist/web/assets/metadataRegistry-7DDoxaR3.js +1 -0
  81. package/dist/web/assets/{providersData-DRVJJUB4.js → providersData-Br5RocnM.js} +1 -1
  82. package/dist/web/index.html +2 -2
  83. package/package.json +1 -1
  84. package/dist/web/assets/EditAccountModal-65P5phzh.js +0 -1
  85. package/dist/web/assets/MitmTab-Bl-E-IDY.js +0 -14
  86. package/dist/web/assets/ModelAutocompleteInput-COe36ge6.js +0 -1
  87. package/dist/web/assets/ProviderDetailPage-BnQ7kK6s.js +0 -6
  88. package/dist/web/assets/QuotaTab-DkRBaW79.js +0 -1
  89. package/dist/web/assets/SettingsTab-DPcPmPUd.js +0 -1
  90. package/dist/web/assets/UsageTab-Danjts5j.js +0 -1
  91. package/dist/web/assets/index-CeC7GeyM.js +0 -2
  92. package/dist/web/assets/index-YgSWkEbZ.css +0 -1
  93. package/dist/web/assets/metadataRegistry-Dxrq24qH.js +0 -1
@@ -0,0 +1,80 @@
1
+ import crypto from "node:crypto";
2
+ const DNS_NAMESPACE_BYTES = Buffer.from("6ba7b8109dad11d180b400c04fd430c8", "hex");
3
+ export function generateHashed64Hex(input, salt = "") {
4
+ return crypto.createHash("sha256").update(input + salt).digest("hex");
5
+ }
6
+ export function generateSessionId(authToken) {
7
+ const hash = crypto.createHash("sha1").update(DNS_NAMESPACE_BYTES).update(authToken).digest();
8
+ hash[6] = (hash[6] & 0x0f) | 0x50; // Version 5
9
+ hash[8] = (hash[8] & 0x3f) | 0x80; // Variant RFC 4122
10
+ const hex = hash.subarray(0, 16).toString("hex");
11
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
12
+ }
13
+ export function generateCursorChecksum(machineId) {
14
+ const timestamp = Math.floor(Date.now() / 1000000);
15
+ const byteArray = new Uint8Array([
16
+ (timestamp >> 40) & 0xff,
17
+ (timestamp >> 32) & 0xff,
18
+ (timestamp >> 24) & 0xff,
19
+ (timestamp >> 16) & 0xff,
20
+ (timestamp >> 8) & 0xff,
21
+ timestamp & 0xff,
22
+ ]);
23
+ let t = 165;
24
+ for (let i = 0; i < byteArray.length; i++) {
25
+ byteArray[i] = ((byteArray[i] ^ t) + (i % 256)) & 0xff;
26
+ t = byteArray[i];
27
+ }
28
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
29
+ let encoded = "";
30
+ for (let i = 0; i < byteArray.length; i += 3) {
31
+ const a = byteArray[i];
32
+ const b = i + 1 < byteArray.length ? byteArray[i + 1] : 0;
33
+ const c = i + 2 < byteArray.length ? byteArray[i + 2] : 0;
34
+ encoded += alphabet[a >> 2];
35
+ encoded += alphabet[((a & 3) << 4) | (b >> 4)];
36
+ if (i + 1 < byteArray.length) {
37
+ encoded += alphabet[((b & 15) << 2) | (c >> 6)];
38
+ }
39
+ if (i + 2 < byteArray.length) {
40
+ encoded += alphabet[c & 63];
41
+ }
42
+ }
43
+ return `${encoded}${machineId}`;
44
+ }
45
+ export function buildCursorHeaders(accessToken, machineId, ghostMode = true) {
46
+ const cleanToken = accessToken.includes("::") ? accessToken.split("::")[1] : accessToken;
47
+ const effectiveMachineId = machineId || generateHashed64Hex(cleanToken, "machineId");
48
+ const sessionId = generateSessionId(cleanToken);
49
+ const clientKey = generateHashed64Hex(cleanToken);
50
+ const checksum = generateCursorChecksum(effectiveMachineId);
51
+ let os = "linux";
52
+ if (process.platform === "win32")
53
+ os = "windows";
54
+ else if (process.platform === "darwin")
55
+ os = "macos";
56
+ let arch = "x64";
57
+ if (process.arch === "arm64")
58
+ arch = "aarch64";
59
+ return {
60
+ authorization: `Bearer ${cleanToken}`,
61
+ "connect-accept-encoding": "gzip",
62
+ "connect-protocol-version": "1",
63
+ "content-type": "application/connect+proto",
64
+ "user-agent": "connect-es/1.6.1",
65
+ "x-amzn-trace-id": `Root=${crypto.randomUUID()}`,
66
+ "x-client-key": clientKey,
67
+ "x-cursor-checksum": checksum,
68
+ "x-cursor-client-version": "3.12.17",
69
+ "x-cursor-client-commit": "0fb762053c34788bb7760d5673f8a6d4c8589d50",
70
+ "x-cursor-client-type": "ide",
71
+ "x-cursor-client-os": os,
72
+ "x-cursor-client-arch": arch,
73
+ "x-cursor-client-device-type": "desktop",
74
+ "x-cursor-config-version": crypto.randomUUID(),
75
+ "x-cursor-timezone": Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
76
+ "x-ghost-mode": ghostMode ? "true" : "false",
77
+ "x-request-id": crypto.randomUUID(),
78
+ "x-session-id": sessionId,
79
+ };
80
+ }
@@ -0,0 +1,194 @@
1
+ import crypto from "node:crypto";
2
+ import http2 from "node:http2";
3
+ import { buildCursorHeaders } from "./cursorChecksum.js";
4
+ import { decodeMessage } from "./cursorWire.js";
5
+ const FETCH_TIMEOUT_MS = 10_000;
6
+ const CACHE_TTL_MS = 5 * 60 * 1000;
7
+ const MODEL_ID_FIELD = 1;
8
+ const DISPLAY_MODEL_ID_FIELD = 3;
9
+ const DISPLAY_NAME_FIELD = 4;
10
+ const DISPLAY_NAME_SHORT_FIELD = 5;
11
+ const RESPONSE_MODELS_FIELD = 1;
12
+ const RESPONSE_AVAILABLE_MODELS_FIELD = 2;
13
+ const AVAILABLE_MODEL_NAME_FIELD = 1;
14
+ const AVAILABLE_MODEL_DEFAULT_ON_FIELD = 2;
15
+ const AVAILABLE_MODEL_IS_CHAT_ONLY_FIELD = 4;
16
+ const AVAILABLE_MODEL_SUPPORTS_AGENT_FIELD = 5;
17
+ const AVAILABLE_MODEL_IS_HIDDEN_FIELD = 35;
18
+ const catalogCache = new Map();
19
+ function cacheKey(credentials) {
20
+ const seed = [credentials.machineId, credentials.accessToken].filter(Boolean).join(":");
21
+ if (!seed)
22
+ return "cursor-anonymous";
23
+ return crypto.createHash("sha256").update(`cursor:${seed}`).digest("hex");
24
+ }
25
+ function firstString(fields, fieldNumber) {
26
+ const value = fields.get(fieldNumber)?.[0]?.value;
27
+ if (!value || typeof value === "number")
28
+ return "";
29
+ return Buffer.from(value).toString("utf8");
30
+ }
31
+ function firstBool(fields, fieldNumber) {
32
+ const value = fields.get(fieldNumber)?.[0]?.value;
33
+ return value === 1;
34
+ }
35
+ export function parseCursorUsableModels(payload) {
36
+ const response = decodeMessage(payload);
37
+ const seen = new Set();
38
+ const models = [];
39
+ for (const entry of response.get(RESPONSE_MODELS_FIELD) || []) {
40
+ if (!entry?.value || typeof entry.value === "number")
41
+ continue;
42
+ const detail = decodeMessage(entry.value);
43
+ const id = firstString(detail, MODEL_ID_FIELD).trim();
44
+ if (!id || seen.has(id))
45
+ continue;
46
+ seen.add(id);
47
+ const name = (firstString(detail, DISPLAY_NAME_FIELD) ||
48
+ firstString(detail, DISPLAY_NAME_SHORT_FIELD) ||
49
+ firstString(detail, DISPLAY_MODEL_ID_FIELD) ||
50
+ id).trim();
51
+ models.push({ id, name });
52
+ }
53
+ return models;
54
+ }
55
+ export function parseCursorAvailableModels(payload) {
56
+ const response = decodeMessage(payload);
57
+ const seen = new Set();
58
+ const models = [];
59
+ for (const entry of response.get(RESPONSE_AVAILABLE_MODELS_FIELD) || []) {
60
+ if (!entry?.value || typeof entry.value === "number")
61
+ continue;
62
+ const fields = decodeMessage(entry.value);
63
+ const id = firstString(fields, AVAILABLE_MODEL_NAME_FIELD).trim();
64
+ if (!id || seen.has(id))
65
+ continue;
66
+ seen.add(id);
67
+ models.push({
68
+ id,
69
+ name: id,
70
+ defaultOn: firstBool(fields, AVAILABLE_MODEL_DEFAULT_ON_FIELD),
71
+ isChatOnly: firstBool(fields, AVAILABLE_MODEL_IS_CHAT_ONLY_FIELD),
72
+ supportsAgent: firstBool(fields, AVAILABLE_MODEL_SUPPORTS_AGENT_FIELD),
73
+ isHidden: firstBool(fields, AVAILABLE_MODEL_IS_HIDDEN_FIELD),
74
+ });
75
+ }
76
+ return models;
77
+ }
78
+ export function mergeCursorModelFlags(models, payload) {
79
+ const available = parseCursorAvailableModels(payload);
80
+ if (!available.length || !Array.isArray(models))
81
+ return models;
82
+ const flagsById = new Map(available.map((model) => [model.id, model]));
83
+ return models.map((model) => {
84
+ const flags = flagsById.get(model.id);
85
+ return flags ? { ...model, ...flags } : model;
86
+ });
87
+ }
88
+ export function resolveAutoModelSelection(models) {
89
+ if (!Array.isArray(models) || models.length === 0)
90
+ return null;
91
+ const usable = models.filter((model) => model.supportsAgent && !model.isChatOnly && !model.isHidden);
92
+ if (usable.length === 0)
93
+ return null;
94
+ const preferred = usable.find((model) => model.defaultOn) || usable[0];
95
+ return {
96
+ modelId: preferred.id,
97
+ matchedBy: "auto-default",
98
+ };
99
+ }
100
+ export function http2PostProto(url, headers, body, signal, timeoutMs = FETCH_TIMEOUT_MS) {
101
+ return new Promise((resolve, reject) => {
102
+ const urlObj = new URL(url);
103
+ const client = http2.connect(`https://${urlObj.host}`);
104
+ const chunks = [];
105
+ let responseHeaders = {};
106
+ let settled = false;
107
+ const finish = (fn) => (...args) => {
108
+ if (settled)
109
+ return;
110
+ settled = true;
111
+ clearTimeout(timeoutId);
112
+ try {
113
+ client.close();
114
+ }
115
+ catch { }
116
+ fn(...args);
117
+ };
118
+ const timeoutId = setTimeout(finish(() => reject(new Error("Cursor GetUsableModels timed out"))), timeoutMs);
119
+ client.on("error", finish(reject));
120
+ const req = client.request({
121
+ ":method": "POST",
122
+ ":path": urlObj.pathname,
123
+ ":authority": urlObj.host,
124
+ ":scheme": "https",
125
+ ...headers,
126
+ });
127
+ req.on("response", (hdrs) => {
128
+ responseHeaders = hdrs;
129
+ });
130
+ req.on("data", (chunk) => {
131
+ chunks.push(chunk);
132
+ });
133
+ req.on("end", finish(() => {
134
+ resolve({
135
+ status: Number(responseHeaders[":status"] || 0),
136
+ body: Buffer.concat(chunks),
137
+ });
138
+ }));
139
+ req.on("error", finish(reject));
140
+ if (signal) {
141
+ const onAbort = finish(() => reject(new Error("Request aborted")));
142
+ if (signal.aborted)
143
+ onAbort();
144
+ else
145
+ signal.addEventListener("abort", onAbort, { once: true });
146
+ }
147
+ req.end(body && body.length ? Buffer.from(body) : undefined);
148
+ });
149
+ }
150
+ export async function fetchCursorCatalog(credentials, signal, timeoutMs = FETCH_TIMEOUT_MS) {
151
+ const accessToken = credentials?.accessToken;
152
+ const machineId = credentials?.machineId;
153
+ if (!accessToken)
154
+ throw new Error("Cursor access token is required");
155
+ const url = "https://agent.api5.cursor.sh/agent.v1.AgentService/GetUsableModels";
156
+ const headers = {
157
+ ...buildCursorHeaders(accessToken, machineId, credentials?.ghostMode !== false),
158
+ accept: "application/proto",
159
+ "content-type": "application/proto",
160
+ };
161
+ delete headers["connect-accept-encoding"];
162
+ delete headers["connect-protocol-version"];
163
+ const response = await http2PostProto(url, headers, new Uint8Array(), signal, timeoutMs);
164
+ if (response.status !== 200) {
165
+ const error = new Error(`Cursor GetUsableModels returned ${response.status}`);
166
+ error.status = response.status;
167
+ throw error;
168
+ }
169
+ return mergeCursorModelFlags(parseCursorUsableModels(new Uint8Array(response.body)), response.body);
170
+ }
171
+ export async function resolveCursorModels(credentials, options = {}) {
172
+ if (!credentials?.accessToken)
173
+ return null;
174
+ const key = cacheKey(credentials);
175
+ const now = Date.now();
176
+ if (!options.forceRefresh) {
177
+ const cached = catalogCache.get(key);
178
+ if (cached && cached.expiresAt > now)
179
+ return { models: cached.models };
180
+ }
181
+ try {
182
+ const models = await fetchCursorCatalog(credentials, options.signal);
183
+ if (!models?.length)
184
+ return null;
185
+ catalogCache.set(key, { expiresAt: now + CACHE_TTL_MS, models });
186
+ return { models };
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ export function clearCursorModelCache() {
193
+ catalogCache.clear();
194
+ }
@@ -0,0 +1,193 @@
1
+ import crypto from "node:crypto";
2
+ import { WIRE_TYPE, concatBuffers, encodeField, decodeMessage, wrapConnectRPCFrame, agentString, agentMessage, agentBool, extractAgentString, encodeAgentValue, decodeAgentValue, } from "./cursorWire.js";
3
+ export * from "./cursorWire.js";
4
+ // MCP Tool Definition & Args Constants
5
+ const MTD_NAME = 1;
6
+ const MTD_DESCRIPTION = 2;
7
+ const MTD_INPUT_SCHEMA = 3;
8
+ const MTD_PROVIDER = 4;
9
+ const MTD_TOOL_NAME = 5;
10
+ const MCP_TOOLS_TOOL = 1;
11
+ const MCP_ARGS_NAME = 1;
12
+ const MCP_ARGS_ENTRY = 2;
13
+ const MCP_ARGS_CALL_ID = 3;
14
+ const MCP_ARGS_TOOL_NAME = 5;
15
+ const PB_MAP_KEY = 1;
16
+ const PB_MAP_VALUE = 2;
17
+ export function toolNameAndSchema(tool) {
18
+ const fn = tool?.function || tool || {};
19
+ return {
20
+ name: fn.name || tool?.name || "",
21
+ description: fn.description || tool?.description || "",
22
+ schema: fn.parameters || tool?.parameters || tool?.inputSchema || tool?.input_schema || {},
23
+ };
24
+ }
25
+ export function encodeMcpToolDefinition(tool) {
26
+ const { name, description, schema } = toolNameAndSchema(tool);
27
+ return concatBuffers(encodeField(MTD_NAME, WIRE_TYPE.LEN, name), encodeField(MTD_DESCRIPTION, WIRE_TYPE.LEN, description), encodeField(MTD_INPUT_SCHEMA, WIRE_TYPE.LEN, encodeAgentValue(schema)), encodeField(MTD_PROVIDER, WIRE_TYPE.LEN, "mapigate"), encodeField(MTD_TOOL_NAME, WIRE_TYPE.LEN, name));
28
+ }
29
+ export function encodeMcpTools(tools = []) {
30
+ if (!tools?.length)
31
+ return new Uint8Array();
32
+ return concatBuffers(...tools.map((tool) => encodeField(MCP_TOOLS_TOOL, WIRE_TYPE.LEN, encodeMcpToolDefinition(tool))));
33
+ }
34
+ export function decodeMcpArgs(bytes) {
35
+ const msg = decodeMessage(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes));
36
+ const args = {};
37
+ for (const entry of msg.get(MCP_ARGS_ENTRY) || []) {
38
+ const pair = decodeMessage(Buffer.from(entry.value));
39
+ const key = Buffer.from(pair.get(PB_MAP_KEY)?.[0]?.value || []).toString("utf8");
40
+ if (key)
41
+ args[key] = decodeAgentValue(pair.get(PB_MAP_VALUE)?.[0]?.value);
42
+ }
43
+ const read = (field) => Buffer.from(msg.get(field)?.[0]?.value || []).toString("utf8");
44
+ return {
45
+ name: read(MCP_ARGS_NAME),
46
+ toolCallId: read(MCP_ARGS_CALL_ID),
47
+ toolName: read(MCP_ARGS_TOOL_NAME),
48
+ args,
49
+ };
50
+ }
51
+ export function textFromContent(content) {
52
+ if (typeof content === "string")
53
+ return content;
54
+ if (!Array.isArray(content))
55
+ return "";
56
+ return content
57
+ .filter((part) => !part || part.type === "text" || typeof part === "string")
58
+ .map((part) => (typeof part === "string" ? part : String(part?.text ?? "")))
59
+ .join("\n");
60
+ }
61
+ export function isAgentCapableRequest(body) {
62
+ if (!Array.isArray(body?.messages) || body.messages.length === 0)
63
+ return false;
64
+ return body.messages.every((message) => {
65
+ if (Array.isArray(message?.content)) {
66
+ return message.content.every((part) => !part || part.type === "text" || typeof part === "string");
67
+ }
68
+ return message?.content == null || typeof message.content === "string";
69
+ });
70
+ }
71
+ export function encodeHistoryMessage(message) {
72
+ const content = textFromContent(message?.content);
73
+ const extras = [];
74
+ if (message?.role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.length) {
75
+ for (const tc of message.tool_calls) {
76
+ extras.push(`[tool_call id=${tc.id || ""} name=${tc.function?.name || "tool"} args=${tc.function?.arguments || "{}"}]`);
77
+ }
78
+ }
79
+ if (message?.role === "tool") {
80
+ extras.push(`[tool_result id=${message.tool_call_id || ""}]`);
81
+ }
82
+ const textBody = [content, ...extras].filter(Boolean).join("\n");
83
+ if (!textBody)
84
+ return null;
85
+ const text = agentString(1, textBody);
86
+ if (message.role === "assistant") {
87
+ return agentMessage(2, agentMessage(1, agentMessage(1, text)));
88
+ }
89
+ return agentMessage(1, agentMessage(1, agentMessage(1, text)));
90
+ }
91
+ export function buildAgentRunFrame(messages, model, tools = [], reasoningEffort = null) {
92
+ const system = messages
93
+ .filter((message) => message?.role === "system")
94
+ .map((message) => textFromContent(message.content))
95
+ .filter(Boolean)
96
+ .join("\n\n");
97
+ const chatMessages = messages.filter((message) => message?.role !== "system");
98
+ let currentIndex = -1;
99
+ for (let i = chatMessages.length - 1; i >= 0; i--) {
100
+ const role = chatMessages[i]?.role;
101
+ if (role === "user" || role === "tool") {
102
+ currentIndex = i;
103
+ break;
104
+ }
105
+ }
106
+ const current = currentIndex >= 0 ? chatMessages[currentIndex] : chatMessages[chatMessages.length - 1];
107
+ const history = chatMessages
108
+ .slice(0, currentIndex >= 0 ? currentIndex : -1)
109
+ .map(encodeHistoryMessage)
110
+ .filter((entry) => entry !== null);
111
+ const content = textFromContent(current?.content);
112
+ const toolTag = current?.role === "tool" && current.tool_call_id ? `[tool_result id=${current.tool_call_id}]` : "";
113
+ const rawUser = [content, toolTag].filter(Boolean).join("\n") || "Continue.";
114
+ const userText = system ? `${system}\n\n${rawUser}` : rawUser;
115
+ const userMessage = concatBuffers(agentString(1, userText), agentString(2, crypto.randomUUID()), agentMessage(3, new Uint8Array()), encodeField(4, WIRE_TYPE.VARINT, 1));
116
+ const conversationHistory = history.length ? concatBuffers(...history.map((entry) => agentMessage(1, entry))) : null;
117
+ const userAction = concatBuffers(agentMessage(1, userMessage), ...(conversationHistory ? [agentMessage(7, conversationHistory)] : []));
118
+ const conversationAction = agentMessage(1, userAction);
119
+ const effort = String(reasoningEffort || "").toLowerCase();
120
+ const effortValue = effort === "ultra" ? "max" : effort === "minimal" ? "low" : effort;
121
+ const parameter = effortValue && effortValue !== "none"
122
+ ? agentMessage(3, concatBuffers(agentString(1, /gpt-/i.test(model) ? "reasoning" : "effort"), agentString(2, effortValue)))
123
+ : null;
124
+ const requestedModel = concatBuffers(agentString(1, model), agentBool(7, true), ...(parameter ? [parameter] : []));
125
+ const modelDetails = concatBuffers(agentString(1, model), agentString(3, model), agentString(4, model));
126
+ const mcpTools = encodeMcpTools(tools);
127
+ const runRequest = concatBuffers(agentMessage(1, new Uint8Array()), agentMessage(2, conversationAction), agentMessage(3, modelDetails), ...(mcpTools.length ? [agentMessage(4, mcpTools)] : []), agentMessage(9, requestedModel));
128
+ return wrapConnectRPCFrame(agentMessage(1, runRequest));
129
+ }
130
+ export function tailOnlyCursorMessages(messages) {
131
+ if (!Array.isArray(messages) || messages.length === 0)
132
+ return messages || [];
133
+ const systemMessages = messages.filter((message) => message?.role === "system" && !String(message?.content || "").includes("[mapigate]"));
134
+ const chatMessages = messages.filter((message) => message?.role !== "system");
135
+ let anchor = chatMessages.length - 1;
136
+ for (let i = chatMessages.length - 1; i >= 0; i--) {
137
+ if (chatMessages[i]?.role === "user" || chatMessages[i]?.role === "tool") {
138
+ anchor = i;
139
+ break;
140
+ }
141
+ }
142
+ const tailStart = anchor > 0 && chatMessages[anchor - 1]?.role === "assistant" ? anchor - 1 : anchor;
143
+ const tail = chatMessages.slice(Math.max(0, tailStart));
144
+ const note = {
145
+ role: "system",
146
+ content: `[mapigate] Long session: ${messages.length} messages trimmed to latest turn. Answer the current request.`,
147
+ };
148
+ return [...systemMessages, note, ...tail];
149
+ }
150
+ export function execIds(execRequest) {
151
+ const id = Number(execRequest?.get(1)?.[0]?.value || 0);
152
+ const execId = extractAgentString(execRequest, 15);
153
+ return { id, execId };
154
+ }
155
+ export function wrapExecClientMessage(execMsgId, execId, resultField, resultPayload) {
156
+ const parts = [];
157
+ if (execMsgId)
158
+ parts.push(encodeField(1, WIRE_TYPE.VARINT, execMsgId));
159
+ parts.push(agentString(15, execId || ""));
160
+ parts.push(encodeField(resultField, WIRE_TYPE.LEN, resultPayload || new Uint8Array()));
161
+ return wrapConnectRPCFrame(agentMessage(2, concatBuffers(...parts)));
162
+ }
163
+ export function createRequestContextResponse(execRequest) {
164
+ const { id, execId } = execIds(execRequest);
165
+ const requestContextSuccess = agentMessage(1, new Uint8Array());
166
+ const requestContextResult = agentMessage(1, requestContextSuccess);
167
+ return wrapExecClientMessage(id, execId, 10, requestContextResult);
168
+ }
169
+ const EXEC_RESULT_FIELD = {
170
+ 2: 2, 3: 3, 4: 4, 5: 5, 7: 7, 8: 8, 9: 9, 16: 16, 20: 20, 23: 23,
171
+ };
172
+ export function rejectExecRequest(execRequest) {
173
+ const { id, execId } = execIds(execRequest);
174
+ const variant = [...(execRequest?.keys() || [])].find((field) => field !== 1 && field !== 15);
175
+ if (!variant)
176
+ return null;
177
+ const resultField = EXEC_RESULT_FIELD[variant];
178
+ if (!resultField)
179
+ return null;
180
+ if (variant === 9)
181
+ return wrapExecClientMessage(id, execId, 9, new Uint8Array());
182
+ const rejected = agentMessage(2, agentString(2, "Tool not available in this environment. Use the MCP tools provided instead."));
183
+ return wrapExecClientMessage(id, execId, resultField, rejected);
184
+ }
185
+ export function encodeKvClientMessage(kvId, resultField, resultPayload, metadata) {
186
+ const parts = [];
187
+ if (kvId)
188
+ parts.push(encodeField(1, WIRE_TYPE.VARINT, kvId));
189
+ parts.push(encodeField(resultField, WIRE_TYPE.LEN, resultPayload || new Uint8Array()));
190
+ if (metadata && metadata.length)
191
+ parts.push(encodeField(4, WIRE_TYPE.LEN, metadata));
192
+ return wrapConnectRPCFrame(agentMessage(3, concatBuffers(...parts)));
193
+ }
@@ -0,0 +1,118 @@
1
+ import http2 from "node:http2";
2
+ export const AGENT_RUN_URL = "https://agent.api5.cursor.sh/agent.v1.AgentService/Run";
3
+ export const TAIL_ONLY_THRESHOLD = 80;
4
+ export function isComposerModel(model) {
5
+ const modelId = String(model || "").split("/").pop() || "";
6
+ return /^composer(?:-|$)/i.test(modelId);
7
+ }
8
+ export function visibleComposerContentFromThinking(thinking) {
9
+ if (!thinking)
10
+ return "";
11
+ const endTag = "</think>";
12
+ const endIdx = thinking.lastIndexOf(endTag);
13
+ if (endIdx < 0)
14
+ return "";
15
+ return thinking.slice(endIdx + endTag.length).trimStart();
16
+ }
17
+ export function openAgentHttp2Stream(url, headers, signal) {
18
+ const urlObj = new URL(url);
19
+ const client = http2.connect(`https://${urlObj.host}`);
20
+ const chunkQueue = [];
21
+ let waiting = null;
22
+ let ended = false;
23
+ let streamError = null;
24
+ let req = null;
25
+ const wake = (result) => {
26
+ if (!waiting)
27
+ return;
28
+ const resolve = waiting;
29
+ waiting = null;
30
+ resolve(result);
31
+ };
32
+ const fail = (error) => {
33
+ if (streamError)
34
+ return;
35
+ streamError = error;
36
+ ended = true;
37
+ wake(null);
38
+ };
39
+ const close = () => {
40
+ try {
41
+ req?.destroy();
42
+ }
43
+ catch { }
44
+ try {
45
+ client.close();
46
+ }
47
+ catch { }
48
+ };
49
+ client.on("error", fail);
50
+ req = client.request({
51
+ ":method": "POST",
52
+ ":path": urlObj.pathname,
53
+ ":authority": urlObj.host,
54
+ ":scheme": "https",
55
+ ...headers,
56
+ });
57
+ req.on("error", fail);
58
+ req.on("data", (chunk) => {
59
+ if (waiting)
60
+ wake({ value: chunk, done: false });
61
+ else
62
+ chunkQueue.push(chunk);
63
+ });
64
+ req.on("end", () => {
65
+ ended = true;
66
+ wake({ value: undefined, done: true });
67
+ });
68
+ if (signal) {
69
+ const onAbort = () => {
70
+ fail(new Error("Request aborted"));
71
+ close();
72
+ };
73
+ if (signal.aborted)
74
+ onAbort();
75
+ else
76
+ signal.addEventListener("abort", onAbort, { once: true });
77
+ }
78
+ const responseHeaders = new Promise((resolve, reject) => {
79
+ const onEarlyError = (error) => reject(error);
80
+ client.once("error", onEarlyError);
81
+ req.once("error", onEarlyError);
82
+ req.once("response", (hdrs) => {
83
+ client.off("error", onEarlyError);
84
+ req.off("error", onEarlyError);
85
+ resolve(hdrs);
86
+ });
87
+ });
88
+ return {
89
+ responseHeaders,
90
+ write(frame) {
91
+ if (req && !req.destroyed)
92
+ req.write(Buffer.from(frame));
93
+ },
94
+ end() {
95
+ try {
96
+ if (req && !req.destroyed)
97
+ req.end();
98
+ }
99
+ catch { }
100
+ },
101
+ close,
102
+ async read() {
103
+ if (chunkQueue.length)
104
+ return { value: chunkQueue.shift(), done: false };
105
+ if (ended) {
106
+ if (streamError)
107
+ throw streamError;
108
+ return { value: undefined, done: true };
109
+ }
110
+ const result = await new Promise((resolve) => {
111
+ waiting = resolve;
112
+ });
113
+ if (streamError)
114
+ throw streamError;
115
+ return result || { value: undefined, done: true };
116
+ },
117
+ };
118
+ }