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.
- package/README.md +7 -1
- package/dist/core/adapters/anthropic/streamAnthropicToOpenAi.js +94 -13
- package/dist/core/adapters/anthropic/types.js +3 -1
- package/dist/core/adapters/anthropicAdapter.js +2 -2
- package/dist/core/adapters/helpers/toolCallRescue.js +224 -10
- package/dist/core/adapters/responsesAdapter.js +56 -3
- package/dist/core/resilience/index.js +5 -0
- package/dist/core/router/earliestResetComparator.js +14 -4
- package/dist/core/router/loadBalancer.js +27 -3
- package/dist/core/scanner/modelScanner.js +8 -1
- package/dist/core/scanner/payloadExtractor.js +8 -3
- package/dist/core/scanner/urlResolver.js +10 -2
- package/dist/core/usage/quotaService.js +3 -1
- package/dist/providers/catalog/xiaomi-tokenplan/metadata.js +6 -1
- package/dist/providers/catalog/xiaomi-tokenplan/provider.js +71 -1
- package/dist/providers/core/base/baseProvider.js +1 -0
- package/dist/providers/runtime/antigravity/executor.js +1 -1
- package/dist/providers/runtime/antigravity/metadata.js +4 -3
- package/dist/providers/runtime/antigravity/provider.js +2 -2
- package/dist/providers/runtime/antigravity/quota.js +9 -3
- package/dist/providers/runtime/antigravity/routes.js +2 -2
- package/dist/providers/runtime/antigravity/types.js +10 -2
- package/dist/providers/runtime/antigravity/weekly.js +1 -1
- package/dist/providers/runtime/codex/models.js +1 -6
- package/dist/providers/runtime/codex/routes.js +40 -24
- package/dist/providers/runtime/cursor/cursorChecksum.js +80 -0
- package/dist/providers/runtime/cursor/cursorModels.js +194 -0
- package/dist/providers/runtime/cursor/cursorProtobuf.js +193 -0
- package/dist/providers/runtime/cursor/cursorSession.js +118 -0
- package/dist/providers/runtime/cursor/cursorStreamer.js +250 -0
- package/dist/providers/runtime/cursor/cursorWire.js +243 -0
- package/dist/providers/runtime/cursor/executor.js +129 -0
- package/dist/providers/runtime/cursor/index.js +6 -0
- package/dist/providers/runtime/cursor/provider.js +34 -10
- package/dist/providers/runtime/cursor-api/auth.js +47 -102
- package/dist/providers/runtime/cursor-api/metadata.js +4 -4
- package/dist/providers/runtime/cursor-api/provider.js +58 -21
- package/dist/providers/runtime/gemini-cli/provider.js +2 -2
- package/dist/providers/runtime/kiro/executor.js +4 -2
- package/dist/providers/runtime/kiro/metadata.js +2 -2
- package/dist/providers/runtime/mimo/metadata.js +1 -0
- package/dist/providers/runtime/mimo/provider.js +56 -0
- package/dist/server/index.js +10 -1
- package/dist/server/proxy/executorHelpers.js +12 -2
- package/dist/server/proxy/singleModelExecutor.js +2 -0
- package/dist/server/proxy/streaming/sseStreamer.js +7 -2
- package/dist/server/routes/apiModels.js +60 -0
- package/dist/server/routes/apiProviders.js +50 -9
- package/dist/server/routes/apiServer.js +110 -0
- package/dist/server/routes/apiSettings.js +35 -7
- package/dist/server/routes/apiUsage.js +5 -3
- package/dist/shared/constants/quotaOrder.js +1 -0
- package/dist/storage/database.js +31 -0
- package/dist/storage/repositories/accountModelRepo.js +108 -0
- package/dist/storage/repositories/logRepo.js +71 -10
- package/dist/storage/repositories/providerRepo.js +69 -59
- package/dist/storage/repositories/requestDetailsRepo.js +8 -0
- package/dist/storage/repositories/settingsRepo.js +17 -0
- package/dist/storage/repositories/usageRepo.js +228 -72
- package/dist/web/assets/{CliToolsTab-DE48Y4QZ.js → CliToolsTab-BzhczMaa.js} +1 -1
- package/dist/web/assets/{CombosTab-dsZhV95u.js → CombosTab-Cz8KYH4M.js} +1 -1
- package/dist/web/assets/{ConfirmModal-BTwfpfgO.js → ConfirmModal-BU1PPpF0.js} +1 -1
- package/dist/web/assets/{ConsoleLogTab-DtUTPoi7.js → ConsoleLogTab-CFvXde1l.js} +1 -1
- package/dist/web/assets/EditAccountModal-CS2TR4bt.js +1 -0
- package/dist/web/assets/{EndpointTab-Ya1KYJSp.js → EndpointTab-DZCRpAbh.js} +1 -1
- package/dist/web/assets/{MitmTab-Bl-E-IDY.js → MitmTab-CTfwqdey.js} +1 -1
- package/dist/web/assets/{ModelAutocompleteInput-COe36ge6.js → ModelAutocompleteInput-CAi2R2s9.js} +1 -1
- package/dist/web/assets/ProviderDetailPage-Dv2LpFj_.js +6 -0
- package/dist/web/assets/{ProvidersTab-COC-cJXg.js → ProvidersTab-DwHMHdPu.js} +1 -1
- package/dist/web/assets/QuotaTab-DS1y9gGp.js +1 -0
- package/dist/web/assets/SettingsTab-DULcs9O4.js +1 -0
- package/dist/web/assets/UsageTab-DKBaBAeT.js +1 -0
- package/dist/web/assets/index-BisuNW2y.css +1 -0
- package/dist/web/assets/index-DPdrZakW.js +2 -0
- package/dist/web/assets/metadataRegistry-7DDoxaR3.js +1 -0
- package/dist/web/assets/{providersData-DRVJJUB4.js → providersData-Br5RocnM.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/EditAccountModal-65P5phzh.js +0 -1
- package/dist/web/assets/ProviderDetailPage-BnQ7kK6s.js +0 -6
- package/dist/web/assets/QuotaTab-DkRBaW79.js +0 -1
- package/dist/web/assets/SettingsTab-DPcPmPUd.js +0 -1
- package/dist/web/assets/UsageTab-Danjts5j.js +0 -1
- package/dist/web/assets/index-CeC7GeyM.js +0 -2
- package/dist/web/assets/index-YgSWkEbZ.css +0 -1
- package/dist/web/assets/metadataRegistry-Dxrq24qH.js +0 -1
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
[](LICENSE)
|
|
14
14
|
[](#)
|
|
15
15
|
[](https://www.typescriptlang.org/)
|
|
16
|
-
[](package.json)
|
|
17
17
|
|
|
18
18
|
[**What is Mapigate?**](#-what-is-mapigate) • [**Gateway API**](#-gateway-api) • [**Supported Providers**](#-supported-providers-151) • [**Quick Start**](#-quick-start-get-running-in-60s) • [**Token Saver**](#-feature-1-token-saver-modular-token-optimization) • [**Smart Routing & Combos**](#-feature-2-smart-routing--combo-engine) • [**Connect Coding Tools**](#-feature-3-one-click-connection-for-26-coding-assistants) • [**MITM Interceptor**](#-feature-4-mitm-https-interceptor-for-closed-tools) • [**Web Dashboard**](#-feature-5-web-dashboard-tour) • [**CLI Reference**](#-cli-reference-mapigate--mpg)
|
|
19
19
|
|
|
@@ -141,6 +141,12 @@ Per provider you can configure multiple accounts with `round-robin` (default) or
|
|
|
141
141
|
|
|
142
142
|
Requires **Node.js `>= 22.5.0`** (Node 22 LTS recommended for built-in `node:sqlite` WAL engine):
|
|
143
143
|
|
|
144
|
+
#### Option A: Install via npm (Recommended)
|
|
145
|
+
```bash
|
|
146
|
+
npm install -g mapigate
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
#### Option B: From Source
|
|
144
150
|
```bash
|
|
145
151
|
# Clone the repository
|
|
146
152
|
git clone https://github.com/joutvhu/mapigate.git
|
|
@@ -40,18 +40,53 @@ export function anthropicChunkToOpenAiEvent(event, requestId, state, streamState
|
|
|
40
40
|
}
|
|
41
41
|
else if (event.type === "content_block_delta") {
|
|
42
42
|
if (event.delta?.type === "text_delta" && event.delta.text) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
43
|
+
const rescuer = streamState.toolRescuer;
|
|
44
|
+
const { calls, cleanText } = rescuer
|
|
45
|
+
? rescuer.feed(event.delta.text)
|
|
46
|
+
: { calls: [], cleanText: event.delta.text };
|
|
47
|
+
if (calls.length > 0) {
|
|
48
|
+
for (const c of calls) {
|
|
49
|
+
const toolIdx = streamState.toolCallIndex++;
|
|
50
|
+
events.push(`data: ${JSON.stringify({
|
|
51
|
+
id: chunkId,
|
|
52
|
+
object: "chat.completion.chunk",
|
|
53
|
+
created,
|
|
54
|
+
choices: [
|
|
55
|
+
{
|
|
56
|
+
index: 0,
|
|
57
|
+
delta: {
|
|
58
|
+
tool_calls: [
|
|
59
|
+
{
|
|
60
|
+
index: toolIdx,
|
|
61
|
+
id: `call_${Date.now()}_${toolIdx}`,
|
|
62
|
+
type: "function",
|
|
63
|
+
function: {
|
|
64
|
+
name: c.name,
|
|
65
|
+
arguments: c.arguments,
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
finish_reason: null,
|
|
71
|
+
},
|
|
72
|
+
],
|
|
73
|
+
})}\n\n`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (cleanText) {
|
|
77
|
+
events.push(`data: ${JSON.stringify({
|
|
78
|
+
id: chunkId,
|
|
79
|
+
object: "chat.completion.chunk",
|
|
80
|
+
created,
|
|
81
|
+
choices: [
|
|
82
|
+
{
|
|
83
|
+
index: 0,
|
|
84
|
+
delta: { content: cleanText },
|
|
85
|
+
finish_reason: null,
|
|
86
|
+
},
|
|
87
|
+
],
|
|
88
|
+
})}\n\n`);
|
|
89
|
+
}
|
|
55
90
|
}
|
|
56
91
|
else if (event.delta?.type === "thinking_delta" && event.delta.thinking) {
|
|
57
92
|
events.push(`data: ${JSON.stringify({
|
|
@@ -128,10 +163,56 @@ export function anthropicChunkToOpenAiEvent(event, requestId, state, streamState
|
|
|
128
163
|
})}\n\n`);
|
|
129
164
|
}
|
|
130
165
|
else if (event.type === "message_delta") {
|
|
166
|
+
if (streamState.toolRescuer) {
|
|
167
|
+
const { calls, cleanText } = streamState.toolRescuer.flush();
|
|
168
|
+
if (calls.length > 0) {
|
|
169
|
+
for (const c of calls) {
|
|
170
|
+
const toolIdx = streamState.toolCallIndex++;
|
|
171
|
+
events.push(`data: ${JSON.stringify({
|
|
172
|
+
id: chunkId,
|
|
173
|
+
object: "chat.completion.chunk",
|
|
174
|
+
created,
|
|
175
|
+
choices: [
|
|
176
|
+
{
|
|
177
|
+
index: 0,
|
|
178
|
+
delta: {
|
|
179
|
+
tool_calls: [
|
|
180
|
+
{
|
|
181
|
+
index: toolIdx,
|
|
182
|
+
id: `call_${Date.now()}_${toolIdx}`,
|
|
183
|
+
type: "function",
|
|
184
|
+
function: {
|
|
185
|
+
name: c.name,
|
|
186
|
+
arguments: c.arguments,
|
|
187
|
+
},
|
|
188
|
+
},
|
|
189
|
+
],
|
|
190
|
+
},
|
|
191
|
+
finish_reason: null,
|
|
192
|
+
},
|
|
193
|
+
],
|
|
194
|
+
})}\n\n`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (cleanText) {
|
|
198
|
+
events.push(`data: ${JSON.stringify({
|
|
199
|
+
id: chunkId,
|
|
200
|
+
object: "chat.completion.chunk",
|
|
201
|
+
created,
|
|
202
|
+
choices: [
|
|
203
|
+
{
|
|
204
|
+
index: 0,
|
|
205
|
+
delta: { content: cleanText },
|
|
206
|
+
finish_reason: null,
|
|
207
|
+
},
|
|
208
|
+
],
|
|
209
|
+
})}\n\n`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
131
212
|
const stopReason = event.delta?.stop_reason;
|
|
132
213
|
let finishReason = null;
|
|
133
214
|
if (stopReason === "end_turn")
|
|
134
|
-
finishReason = "stop";
|
|
215
|
+
finishReason = streamState.toolCallIndex > 0 ? "tool_calls" : "stop";
|
|
135
216
|
else if (stopReason === "max_tokens")
|
|
136
217
|
finishReason = "length";
|
|
137
218
|
else if (stopReason === "tool_use")
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { toolSchemaMap } from "../helpers/toolArgsRepair.js";
|
|
2
|
+
import { createStreamToolCallRescuer } from "../helpers/toolCallRescue.js";
|
|
2
3
|
export function createStreamState(messageId, tools) {
|
|
3
4
|
return {
|
|
4
5
|
messageStartSent: false,
|
|
@@ -11,12 +12,13 @@ export function createStreamState(messageId, tools) {
|
|
|
11
12
|
toolSchemas: tools ? toolSchemaMap(tools) : undefined,
|
|
12
13
|
};
|
|
13
14
|
}
|
|
14
|
-
export function createAnthropicToOpenAiState() {
|
|
15
|
+
export function createAnthropicToOpenAiState(toolNames) {
|
|
15
16
|
return {
|
|
16
17
|
toolCallIndex: 0,
|
|
17
18
|
blockIndexToToolCallIndex: new Map(),
|
|
18
19
|
promptTokens: 0,
|
|
19
20
|
cachedTokens: 0,
|
|
20
21
|
cacheCreationTokens: 0,
|
|
22
|
+
toolRescuer: toolNames ? createStreamToolCallRescuer(toolNames) : undefined,
|
|
21
23
|
};
|
|
22
24
|
}
|
|
@@ -23,8 +23,8 @@ export class AnthropicAdapter {
|
|
|
23
23
|
/**
|
|
24
24
|
* Create a state tracker for Anthropic -> OpenAI streaming
|
|
25
25
|
*/
|
|
26
|
-
static createAnthropicToOpenAiState() {
|
|
27
|
-
return createAnthropicToOpenAiState();
|
|
26
|
+
static createAnthropicToOpenAiState(toolNames) {
|
|
27
|
+
return createAnthropicToOpenAiState(toolNames);
|
|
28
28
|
}
|
|
29
29
|
/**
|
|
30
30
|
* Convert Anthropic /v1/messages payload to OpenAI /v1/chat/completions payload
|
|
@@ -84,9 +84,9 @@ export function extractBalancedJson(text, from) {
|
|
|
84
84
|
}
|
|
85
85
|
return null;
|
|
86
86
|
}
|
|
87
|
-
const isKnownTool = (name, toolNames) => toolNames.has(name);
|
|
87
|
+
const isKnownTool = (name, toolNames) => toolNames !== undefined ? (toolNames.size === 0 ? false : toolNames.has(name)) : true;
|
|
88
88
|
/** Parse `{"name": ..., "arguments"|"parameters": ...}` into a call. */
|
|
89
|
-
function callFromNamedJson(json, toolNames) {
|
|
89
|
+
export function callFromNamedJson(json, toolNames) {
|
|
90
90
|
let obj;
|
|
91
91
|
try {
|
|
92
92
|
obj = JSON.parse(json);
|
|
@@ -180,9 +180,17 @@ function parseFunctionTagDialect(text, toolNames) {
|
|
|
180
180
|
if (ok)
|
|
181
181
|
calls.push({ name, arguments: extracted.json });
|
|
182
182
|
}
|
|
183
|
+
const closeTag = text.indexOf("</function>", extracted?.end ?? m.index + m[0].length);
|
|
184
|
+
if (!ok && closeTag !== -1) {
|
|
185
|
+
const block = text.slice(m.index, closeTag + "</function>".length);
|
|
186
|
+
const call = parseMimoFunctionAndParameters(block, toolNames);
|
|
187
|
+
if (call) {
|
|
188
|
+
calls.push(call);
|
|
189
|
+
ok = true;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
183
192
|
if (!ok)
|
|
184
193
|
parsedAll = false;
|
|
185
|
-
const closeTag = text.indexOf("</function>", extracted?.end ?? m.index + m[0].length);
|
|
186
194
|
spans.push({
|
|
187
195
|
from: m.index,
|
|
188
196
|
to: closeTag === -1 ? (extracted?.end ?? m.index + m[0].length) : closeTag + "</function>".length,
|
|
@@ -193,25 +201,231 @@ function parseFunctionTagDialect(text, toolNames) {
|
|
|
193
201
|
}
|
|
194
202
|
return { calls: parsedAll && calls.length > 0 ? calls : null, cleanText: clean.trim() };
|
|
195
203
|
}
|
|
204
|
+
export function parseMimoFunctionAndParameters(inner, toolNames) {
|
|
205
|
+
const fnMatch = /<function=([A-Za-z0-9_.-]+)>/i.exec(inner);
|
|
206
|
+
if (!fnMatch)
|
|
207
|
+
return null;
|
|
208
|
+
const name = fnMatch[1].trim();
|
|
209
|
+
if (!isKnownTool(name, toolNames)) {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
const afterFn = inner.slice(fnMatch.index + fnMatch[0].length);
|
|
213
|
+
const paramRegex = /<parameter=([A-Za-z0-9_.-]+)>/gi;
|
|
214
|
+
const paramMatches = [];
|
|
215
|
+
let pm;
|
|
216
|
+
while ((pm = paramRegex.exec(afterFn)) !== null) {
|
|
217
|
+
paramMatches.push({
|
|
218
|
+
key: pm[1].trim(),
|
|
219
|
+
start: pm.index + pm[0].length,
|
|
220
|
+
end: pm.index,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
const argsObj = {};
|
|
224
|
+
for (let i = 0; i < paramMatches.length; i++) {
|
|
225
|
+
const curr = paramMatches[i];
|
|
226
|
+
const nextStart = i + 1 < paramMatches.length ? paramMatches[i + 1].end : afterFn.length;
|
|
227
|
+
let rawVal = afterFn.slice(curr.start, nextStart).trim();
|
|
228
|
+
rawVal = rawVal.replace(/(?:<\/(?:parameter|function|tool_call|invoke|tool_use)>\s*)+$/i, "").trim();
|
|
229
|
+
let val = rawVal;
|
|
230
|
+
if ((rawVal.startsWith("{") && rawVal.endsWith("}")) ||
|
|
231
|
+
(rawVal.startsWith("[") && rawVal.endsWith("]")) ||
|
|
232
|
+
rawVal === "true" ||
|
|
233
|
+
rawVal === "false" ||
|
|
234
|
+
rawVal === "null" ||
|
|
235
|
+
(!isNaN(Number(rawVal)) && rawVal !== "")) {
|
|
236
|
+
try {
|
|
237
|
+
val = JSON.parse(rawVal);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
val = rawVal;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
argsObj[curr.key] = val;
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
name,
|
|
247
|
+
arguments: JSON.stringify(argsObj),
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
export function parseAnyToolBlock(raw, toolNames) {
|
|
251
|
+
if (!raw || typeof raw !== "string")
|
|
252
|
+
return null;
|
|
253
|
+
const trimmed = raw.trim();
|
|
254
|
+
// 1. JSON object format: {"name": ..., "arguments"|"parameters": ...}
|
|
255
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
256
|
+
const jsonCall = callFromNamedJson(trimmed, toolNames);
|
|
257
|
+
if (jsonCall)
|
|
258
|
+
return jsonCall;
|
|
259
|
+
}
|
|
260
|
+
// 2. MiMo / Hermes parameter format: <function=NAME><parameter=KEY>VALUE...
|
|
261
|
+
const mimoCall = parseMimoFunctionAndParameters(trimmed, toolNames);
|
|
262
|
+
if (mimoCall)
|
|
263
|
+
return mimoCall;
|
|
264
|
+
// 3. Anthropic XML format: <invoke name="NAME">... or <tool_use><name>NAME</name>...
|
|
265
|
+
const invokeMatch = /<(?:invoke|function)\s+(?:name|call)=["']?([A-Za-z0-9_.-]+)["']?>/i.exec(trimmed);
|
|
266
|
+
if (invokeMatch) {
|
|
267
|
+
const name = invokeMatch[1].trim();
|
|
268
|
+
if (!isKnownTool(name, toolNames))
|
|
269
|
+
return null;
|
|
270
|
+
const body = trimmed.slice(invokeMatch.index + invokeMatch[0].length);
|
|
271
|
+
const paramRegex = /<parameter\s+name=["']?([A-Za-z0-9_.-]+)["']?>([\s\S]*?)<\/parameter>/gi;
|
|
272
|
+
const argsObj = {};
|
|
273
|
+
let pm;
|
|
274
|
+
let found = false;
|
|
275
|
+
while ((pm = paramRegex.exec(body)) !== null) {
|
|
276
|
+
found = true;
|
|
277
|
+
const key = pm[1].trim();
|
|
278
|
+
const rawVal = pm[2].trim();
|
|
279
|
+
let val = rawVal;
|
|
280
|
+
try {
|
|
281
|
+
val = JSON.parse(rawVal);
|
|
282
|
+
}
|
|
283
|
+
catch { }
|
|
284
|
+
argsObj[key] = val;
|
|
285
|
+
}
|
|
286
|
+
if (found) {
|
|
287
|
+
return { name, arguments: JSON.stringify(argsObj) };
|
|
288
|
+
}
|
|
289
|
+
const argsMatch = /<arguments>([\s\S]*?)<\/arguments>/i.exec(body);
|
|
290
|
+
if (argsMatch) {
|
|
291
|
+
const rawArgs = argsMatch[1].trim();
|
|
292
|
+
try {
|
|
293
|
+
JSON.parse(rawArgs);
|
|
294
|
+
return { name, arguments: rawArgs };
|
|
295
|
+
}
|
|
296
|
+
catch { }
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const toolUseMatch = /<tool_use>[\s\S]*?<name>([A-Za-z0-9_.-]+)<\/name>/i.exec(trimmed);
|
|
300
|
+
if (toolUseMatch) {
|
|
301
|
+
const name = toolUseMatch[1].trim();
|
|
302
|
+
if (isKnownTool(name, toolNames)) {
|
|
303
|
+
const argsMatch = /<arguments>([\s\S]*?)<\/arguments>/i.exec(trimmed);
|
|
304
|
+
if (argsMatch) {
|
|
305
|
+
const rawArgs = argsMatch[1].trim();
|
|
306
|
+
try {
|
|
307
|
+
JSON.parse(rawArgs);
|
|
308
|
+
return { name, arguments: rawArgs };
|
|
309
|
+
}
|
|
310
|
+
catch { }
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
export function createStreamToolCallRescuer(toolNames) {
|
|
317
|
+
let buffer = "";
|
|
318
|
+
let inBlock = false;
|
|
319
|
+
let closeTag = "</tool_call>";
|
|
320
|
+
const TAG_PAIRS = [
|
|
321
|
+
{ open: /<tool_call>/i, close: "</tool_call>" },
|
|
322
|
+
{ open: /<function[=> ]/i, close: "</function>" },
|
|
323
|
+
{ open: /<tool_use>/i, close: "</tool_use>" },
|
|
324
|
+
{ open: /<invoke[> ]/i, close: "</invoke>" },
|
|
325
|
+
];
|
|
326
|
+
function processBuffer() {
|
|
327
|
+
const calls = [];
|
|
328
|
+
let textOut = "";
|
|
329
|
+
while (buffer.length > 0) {
|
|
330
|
+
if (inBlock) {
|
|
331
|
+
const closeIdx = buffer.indexOf(closeTag);
|
|
332
|
+
if (closeIdx === -1) {
|
|
333
|
+
// Block is incomplete, keep all in buffer
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
const block = buffer.slice(0, closeIdx + closeTag.length);
|
|
337
|
+
buffer = buffer.slice(closeIdx + closeTag.length);
|
|
338
|
+
inBlock = false;
|
|
339
|
+
const call = parseAnyToolBlock(block, toolNames);
|
|
340
|
+
if (call) {
|
|
341
|
+
calls.push(call);
|
|
342
|
+
}
|
|
343
|
+
else {
|
|
344
|
+
// If unparseable, don't drop content, return as text
|
|
345
|
+
textOut += block;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
// Search for opening tag
|
|
350
|
+
let earliestMatch = null;
|
|
351
|
+
for (const pair of TAG_PAIRS) {
|
|
352
|
+
const m = buffer.match(pair.open);
|
|
353
|
+
if (m && m.index !== undefined) {
|
|
354
|
+
if (!earliestMatch || m.index < earliestMatch.index) {
|
|
355
|
+
earliestMatch = { index: m.index, length: m[0].length, close: pair.close };
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (!earliestMatch) {
|
|
360
|
+
// No tag found in buffer. Check if buffer ends with a potential opening tag prefix (e.g. "<", "<tool", etc.)
|
|
361
|
+
const partialMatch = /<[a-z_0-9=-]*$/i.exec(buffer);
|
|
362
|
+
if (partialMatch) {
|
|
363
|
+
const safeLen = partialMatch.index;
|
|
364
|
+
textOut += buffer.slice(0, safeLen);
|
|
365
|
+
buffer = buffer.slice(safeLen);
|
|
366
|
+
}
|
|
367
|
+
else {
|
|
368
|
+
textOut += buffer;
|
|
369
|
+
buffer = "";
|
|
370
|
+
}
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
// Emit text before opening tag
|
|
374
|
+
if (earliestMatch.index > 0) {
|
|
375
|
+
textOut += buffer.slice(0, earliestMatch.index);
|
|
376
|
+
}
|
|
377
|
+
buffer = buffer.slice(earliestMatch.index);
|
|
378
|
+
inBlock = true;
|
|
379
|
+
closeTag = earliestMatch.close;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
calls,
|
|
384
|
+
cleanText: textOut.length > 0 ? textOut : null,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
return {
|
|
388
|
+
feed(text) {
|
|
389
|
+
if (!text)
|
|
390
|
+
return { calls: [], cleanText: null };
|
|
391
|
+
buffer += text;
|
|
392
|
+
return processBuffer();
|
|
393
|
+
},
|
|
394
|
+
flush() {
|
|
395
|
+
if (!buffer)
|
|
396
|
+
return { calls: [], cleanText: null };
|
|
397
|
+
if (inBlock) {
|
|
398
|
+
inBlock = false;
|
|
399
|
+
const call = parseAnyToolBlock(buffer, toolNames);
|
|
400
|
+
if (call) {
|
|
401
|
+
buffer = "";
|
|
402
|
+
return { calls: [call], cleanText: null };
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const remaining = buffer;
|
|
406
|
+
buffer = "";
|
|
407
|
+
return { calls: [], cleanText: remaining.length > 0 ? remaining : null };
|
|
408
|
+
},
|
|
409
|
+
};
|
|
410
|
+
}
|
|
196
411
|
/** Dialect 3: <tool_call>{...}</tool_call> XML-JSON blocks. */
|
|
197
412
|
function parseXmlDialect(text, toolNames) {
|
|
198
413
|
const calls = [];
|
|
199
414
|
let parsedAll = true;
|
|
200
415
|
const re = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
|
|
201
416
|
let m;
|
|
202
|
-
let clean = text;
|
|
203
417
|
const matches = [];
|
|
204
418
|
while ((m = re.exec(text)) !== null) {
|
|
205
419
|
matches.push(m[1]);
|
|
206
420
|
}
|
|
207
421
|
for (const inner of matches) {
|
|
208
|
-
|
|
422
|
+
let call = parseAnyToolBlock(inner, toolNames);
|
|
209
423
|
if (call)
|
|
210
424
|
calls.push(call);
|
|
211
425
|
else
|
|
212
426
|
parsedAll = false;
|
|
213
427
|
}
|
|
214
|
-
clean =
|
|
428
|
+
let clean = text.replace(/<tool_call>\s*[\s\S]*?\s*<\/tool_call>/g, "");
|
|
215
429
|
if (/<tool_call>/.test(clean)) {
|
|
216
430
|
parsedAll = false;
|
|
217
431
|
clean = clean.replace(/<tool_call>[\s\S]*$/, "");
|
|
@@ -234,14 +448,14 @@ export function rescueInlineToolCalls(text, toolNames) {
|
|
|
234
448
|
const { calls, cleanText } = parseTokenDialect(text, toolNames);
|
|
235
449
|
return { detected: true, calls, cleanText };
|
|
236
450
|
}
|
|
237
|
-
if (text.includes("<function=")) {
|
|
238
|
-
const { calls, cleanText } = parseFunctionTagDialect(text, toolNames);
|
|
239
|
-
return { detected: true, calls, cleanText };
|
|
240
|
-
}
|
|
241
451
|
if (text.includes("<tool_call>")) {
|
|
242
452
|
const { calls, cleanText } = parseXmlDialect(text, toolNames);
|
|
243
453
|
return { detected: true, calls, cleanText };
|
|
244
454
|
}
|
|
455
|
+
if (text.includes("<function=")) {
|
|
456
|
+
const { calls, cleanText } = parseFunctionTagDialect(text, toolNames);
|
|
457
|
+
return { detected: true, calls, cleanText };
|
|
458
|
+
}
|
|
245
459
|
// Dialect 4: bare or ```json-fenced JSON object naming a known tool
|
|
246
460
|
const trimmed = text.trim();
|
|
247
461
|
const fenced = /^```(?:json)?\s*([\s\S]*?)\s*```$/.exec(trimmed);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { codeWhispererToMessages, extractTools } from "../../mitm/handlers/kiro/converter.js";
|
|
2
|
+
import { createStreamToolCallRescuer, } from "./helpers/toolCallRescue.js";
|
|
2
3
|
/**
|
|
3
4
|
* Normalize Responses API input to array format.
|
|
4
5
|
* Accepts string or array, returns array of message items.
|
|
@@ -186,7 +187,7 @@ export function convertResponsesApiFormat(body) {
|
|
|
186
187
|
}
|
|
187
188
|
return result;
|
|
188
189
|
}
|
|
189
|
-
export function createResponsesStreamState(requestId) {
|
|
190
|
+
export function createResponsesStreamState(requestId, toolNames) {
|
|
190
191
|
return {
|
|
191
192
|
seq: 0,
|
|
192
193
|
started: false,
|
|
@@ -212,6 +213,7 @@ export function createResponsesStreamState(requestId) {
|
|
|
212
213
|
completedSent: false,
|
|
213
214
|
responsesUsage: null,
|
|
214
215
|
completionPending: false,
|
|
216
|
+
toolRescuer: toolNames ? createStreamToolCallRescuer(toolNames) : undefined,
|
|
215
217
|
};
|
|
216
218
|
}
|
|
217
219
|
function toResponsesUsage(usage) {
|
|
@@ -452,6 +454,29 @@ function sendCompleted(state, emit) {
|
|
|
452
454
|
});
|
|
453
455
|
}
|
|
454
456
|
}
|
|
457
|
+
function flushToolRescuer(state, emit) {
|
|
458
|
+
const rescuer = state.toolRescuer;
|
|
459
|
+
if (!rescuer)
|
|
460
|
+
return;
|
|
461
|
+
const { calls, cleanText } = rescuer.flush();
|
|
462
|
+
if (calls.length > 0) {
|
|
463
|
+
for (const c of calls) {
|
|
464
|
+
const tcIdx = (state._rescuedToolIdx = (state._rescuedToolIdx || 0) + 1);
|
|
465
|
+
const callId = `call_${Date.now()}_${tcIdx}`;
|
|
466
|
+
emitToolCall(state, emit, {
|
|
467
|
+
index: tcIdx,
|
|
468
|
+
id: callId,
|
|
469
|
+
function: {
|
|
470
|
+
name: c.name,
|
|
471
|
+
arguments: c.arguments,
|
|
472
|
+
},
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (cleanText) {
|
|
477
|
+
emitTextContent(state, emit, 0, cleanText);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
455
480
|
export function openAiChunkToResponsesEvents(chunk, state) {
|
|
456
481
|
if (!chunk) {
|
|
457
482
|
return finalizeResponsesStream(state);
|
|
@@ -527,8 +552,34 @@ export function openAiChunkToResponsesEvents(chunk, state) {
|
|
|
527
552
|
return events;
|
|
528
553
|
}
|
|
529
554
|
if (content) {
|
|
530
|
-
|
|
531
|
-
|
|
555
|
+
if (state.toolRescuer) {
|
|
556
|
+
const rescuer = state.toolRescuer;
|
|
557
|
+
const { calls, cleanText } = rescuer.feed(content);
|
|
558
|
+
if (calls.length > 0) {
|
|
559
|
+
closeReasoning(state, emit);
|
|
560
|
+
closeMessage(state, emit, idx);
|
|
561
|
+
for (const c of calls) {
|
|
562
|
+
const tcIdx = (state._rescuedToolIdx = (state._rescuedToolIdx || 0) + 1);
|
|
563
|
+
const callId = `call_${Date.now()}_${tcIdx}`;
|
|
564
|
+
emitToolCall(state, emit, {
|
|
565
|
+
index: tcIdx,
|
|
566
|
+
id: callId,
|
|
567
|
+
function: {
|
|
568
|
+
name: c.name,
|
|
569
|
+
arguments: c.arguments,
|
|
570
|
+
},
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
if (cleanText) {
|
|
575
|
+
closeReasoning(state, emit);
|
|
576
|
+
emitTextContent(state, emit, idx, cleanText);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
else {
|
|
580
|
+
closeReasoning(state, emit);
|
|
581
|
+
emitTextContent(state, emit, idx, content);
|
|
582
|
+
}
|
|
532
583
|
}
|
|
533
584
|
}
|
|
534
585
|
// Handle tool calls
|
|
@@ -541,6 +592,7 @@ export function openAiChunkToResponsesEvents(chunk, state) {
|
|
|
541
592
|
}
|
|
542
593
|
// Handle finish reason
|
|
543
594
|
if (choice.finish_reason) {
|
|
595
|
+
flushToolRescuer(state, emit);
|
|
544
596
|
for (const i of Object.keys(state.msgItemAdded).map(Number))
|
|
545
597
|
closeMessage(state, emit, i);
|
|
546
598
|
closeReasoning(state, emit);
|
|
@@ -559,6 +611,7 @@ export function finalizeResponsesStream(state) {
|
|
|
559
611
|
data.sequence_number = nextSeq();
|
|
560
612
|
events.push({ event: eventType, data });
|
|
561
613
|
};
|
|
614
|
+
flushToolRescuer(state, emit);
|
|
562
615
|
// Close any unclosed items
|
|
563
616
|
for (const i of Object.keys(state.msgItemAdded).map(Number))
|
|
564
617
|
closeMessage(state, emit, i);
|
|
@@ -9,6 +9,7 @@ import { ProviderCircuitBreaker, isInfrastructureError } from "./circuitBreaker.
|
|
|
9
9
|
import { ConnectionCooldownManager, isTerminalError, calculateDecorrelatedJitter } from "./cooldownManager.js";
|
|
10
10
|
import { ModelLockoutManager, isModelScopedError } from "./modelLockout.js";
|
|
11
11
|
import { parseRateLimitHeaders } from "../../shared/utils/rateLimitParser.js";
|
|
12
|
+
import { AccountModelRepository } from "../../storage/repositories/accountModelRepo.js";
|
|
12
13
|
export * from "./types.js";
|
|
13
14
|
export { ProviderCircuitBreaker, isInfrastructureError, ConnectionCooldownManager, isTerminalError, calculateDecorrelatedJitter, ModelLockoutManager, isModelScopedError, };
|
|
14
15
|
/**
|
|
@@ -60,6 +61,10 @@ export function recordResilienceSuccess(opts) {
|
|
|
60
61
|
cooldownManager.markSuccess(opts.accountId);
|
|
61
62
|
if (opts.model) {
|
|
62
63
|
modelLockoutManager.recordSuccess(opts.providerId, opts.accountId, opts.model);
|
|
64
|
+
try {
|
|
65
|
+
AccountModelRepository.addAccountModel(opts.accountId, opts.model);
|
|
66
|
+
}
|
|
67
|
+
catch { }
|
|
63
68
|
}
|
|
64
69
|
}
|
|
65
70
|
}
|
|
@@ -49,17 +49,27 @@ export function getAntigravityMetrics(account, targetModel, now = Date.now()) {
|
|
|
49
49
|
}
|
|
50
50
|
const quotas = quotaResult.quotas;
|
|
51
51
|
const isClaudeGptModel = Boolean(targetModel && /claude|gpt/i.test(targetModel));
|
|
52
|
-
const
|
|
52
|
+
const isArgonModel = Boolean(targetModel && /argon/i.test(targetModel));
|
|
53
|
+
const isGeminiModel = Boolean(targetModel && /gemini/i.test(targetModel) && !isArgonModel);
|
|
53
54
|
// Determine target buckets based on model family
|
|
54
55
|
let weeklyBucket;
|
|
55
56
|
let sessionBucket;
|
|
56
|
-
if (
|
|
57
|
+
if (isArgonModel) {
|
|
58
|
+
weeklyBucket = quotas.find((q) => /argon/i.test(q.label) && /weekly/i.test(q.label));
|
|
59
|
+
// Argon only has weekly limit upstream, so sessionBucket remains undefined.
|
|
60
|
+
// Fallback to standard Gemini weekly/session if account has no dedicated Argon quota
|
|
61
|
+
if (!weeklyBucket) {
|
|
62
|
+
weeklyBucket = quotas.find((q) => /gemini/i.test(q.label) && !/argon/i.test(q.label) && /weekly/i.test(q.label));
|
|
63
|
+
sessionBucket = quotas.find((q) => /gemini/i.test(q.label) && !/argon/i.test(q.label) && /5h|session|daily/i.test(q.label));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
else if (isClaudeGptModel) {
|
|
57
67
|
weeklyBucket = quotas.find((q) => /claude|gpt/i.test(q.label) && /weekly/i.test(q.label));
|
|
58
68
|
sessionBucket = quotas.find((q) => /claude|gpt/i.test(q.label) && /5h|session|daily/i.test(q.label));
|
|
59
69
|
}
|
|
60
70
|
else if (isGeminiModel) {
|
|
61
|
-
weeklyBucket = quotas.find((q) => /gemini/i.test(q.label) && /weekly/i.test(q.label));
|
|
62
|
-
sessionBucket = quotas.find((q) => /gemini/i.test(q.label) && /5h|session|daily/i.test(q.label));
|
|
71
|
+
weeklyBucket = quotas.find((q) => /gemini/i.test(q.label) && !/argon/i.test(q.label) && /weekly/i.test(q.label));
|
|
72
|
+
sessionBucket = quotas.find((q) => /gemini/i.test(q.label) && !/argon/i.test(q.label) && /5h|session|daily/i.test(q.label));
|
|
63
73
|
}
|
|
64
74
|
else {
|
|
65
75
|
// If model is unspecified or ambiguous: find earliest resetting weekly bucket with remaining > 0
|
|
@@ -4,6 +4,7 @@ import { cooldownManager, modelLockoutManager, getProviderCircuitBreaker, isRate
|
|
|
4
4
|
import { pickAffinityAccount } from "../caching/promptCacheAffinity.js";
|
|
5
5
|
import { compareAccountsEarliestReset } from "./earliestResetComparator.js";
|
|
6
6
|
import { SequentialSelector } from "./sequentialSelector.js";
|
|
7
|
+
import { AccountModelRepository } from "../../storage/repositories/accountModelRepo.js";
|
|
7
8
|
export { isRateLimitOrQuotaError };
|
|
8
9
|
const SESSION_STICKINESS_TTL_MS = 60 * 60 * 1000; // 1 hour
|
|
9
10
|
const MAX_SESSION_ENTRIES = 5000;
|
|
@@ -67,9 +68,21 @@ export class LoadBalancer {
|
|
|
67
68
|
sessionId = excludeOrOptions.sessionId;
|
|
68
69
|
}
|
|
69
70
|
}
|
|
71
|
+
const targetTag = excludeOrOptions && !(excludeOrOptions instanceof Set) && !Array.isArray(excludeOrOptions)
|
|
72
|
+
? excludeOrOptions.targetTag
|
|
73
|
+
: undefined;
|
|
74
|
+
// Optional tag filtering: if targetTag is specified, narrow allAccounts
|
|
75
|
+
let taggedAccounts = allAccounts;
|
|
76
|
+
if (targetTag) {
|
|
77
|
+
const cleanTag = targetTag.trim().toLowerCase();
|
|
78
|
+
const matched = allAccounts.filter((acc) => (acc.tag || acc.providerSpecificData?.tag)?.trim().toLowerCase() === cleanTag);
|
|
79
|
+
if (matched.length > 0) {
|
|
80
|
+
taggedAccounts = matched;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
70
83
|
const eligibleAccounts = excludeSet
|
|
71
|
-
?
|
|
72
|
-
:
|
|
84
|
+
? taggedAccounts.filter((acc) => !excludeSet.has(acc.id))
|
|
85
|
+
: taggedAccounts;
|
|
73
86
|
if (eligibleAccounts.length === 0)
|
|
74
87
|
return undefined;
|
|
75
88
|
const providerConfig = ProviderRepository.getProviderById(providerId);
|
|
@@ -88,7 +101,18 @@ export class LoadBalancer {
|
|
|
88
101
|
if (healthyOnly && available.length === 0) {
|
|
89
102
|
return undefined;
|
|
90
103
|
}
|
|
91
|
-
|
|
104
|
+
let pool = available.length > 0 ? available : eligibleAccounts;
|
|
105
|
+
// Account-level model capability prioritization:
|
|
106
|
+
// If targetModel is present, partition pool into:
|
|
107
|
+
// Preferred: Accounts that explicitly support this model + unscanned accounts (fail-open)
|
|
108
|
+
// Backup: Accounts confirmed via scan to lack this model
|
|
109
|
+
if (targetModel && pool.length > 1) {
|
|
110
|
+
const classification = AccountModelRepository.classifyAccounts(pool.map((a) => a.id), targetModel);
|
|
111
|
+
const preferred = pool.filter((a) => classification.supported.has(a.id) || classification.unscanned.has(a.id));
|
|
112
|
+
if (preferred.length > 0) {
|
|
113
|
+
pool = preferred;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
92
116
|
// Session Stickiness: 100% Affinity for active sessions with healthy accounts
|
|
93
117
|
// Dynamic strategies like 'earliest-reset' re-evaluate dynamically as account reset windows shift
|
|
94
118
|
if (sessionId && strategy !== "earliest-reset") {
|