mapigate 0.5.133 → 0.5.141
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 +1 -1
- package/dist/cli/commands/logs.js +0 -1
- package/dist/core/adapters/anthropic/requestAnthropicToOpenAi.js +59 -11
- package/dist/core/adapters/anthropic/requestOpenAiToAnthropic.js +1 -1
- package/dist/core/adapters/anthropicAdapter.js +2 -2
- package/dist/core/adapters/helpers/toolCallRescue.js +1 -1
- package/dist/core/adapters/responsesAdapter.js +11 -0
- package/dist/core/capabilities/modelDictionary.js +1 -0
- package/dist/core/scanner/modelScanner.js +2 -1
- package/dist/core/scanner/payloadExtractor.js +1 -1
- package/dist/core/scanner/urlResolver.js +16 -0
- package/dist/core/tokenSaver/methods/rtk/autodetect.js +1 -1
- package/dist/core/tokenSaver/methods/rtk/filters/gitLog.js +1 -1
- package/dist/core/usage/pricing.js +98 -42
- package/dist/core/usage/tokenExtractor.js +59 -0
- package/dist/mitm/handlers/antigravity/config.js +22 -0
- package/dist/mitm/handlers/antigravity/modelInjector.js +2 -2
- package/dist/providers/catalog/commandcode/converter.js +215 -0
- package/dist/providers/catalog/commandcode/executor.js +305 -0
- package/dist/providers/catalog/commandcode/headers.js +76 -0
- package/dist/providers/catalog/commandcode/metadata.js +4 -1
- package/dist/providers/catalog/commandcode/ndjson.js +161 -0
- package/dist/providers/catalog/commandcode/provider.js +18 -35
- package/dist/providers/catalog/commandcode/routes.js +75 -0
- package/dist/providers/catalog/iflow/provider.js +1 -1
- package/dist/providers/catalog/iteracompute/metadata.js +154 -13
- package/dist/providers/catalog/iteracompute/provider.js +111 -0
- package/dist/providers/catalog/opencode-go/metadata.js +4 -2
- package/dist/providers/catalog/opencode-go/models.js +1 -0
- package/dist/providers/catalog/opencode-go/provider.js +114 -0
- package/dist/providers/catalog/opencode-go/quota.js +106 -0
- package/dist/providers/catalog/opencode-go/responses.js +301 -0
- package/dist/providers/catalog/opencode-go/responsesPayload.js +228 -0
- package/dist/providers/catalog/openrouter/metadata.js +1 -0
- package/dist/providers/catalog/sensenova/metadata.js +35 -0
- package/dist/providers/core/base/baseProvider.js +8 -3
- package/dist/providers/core/base/openAiProvider.js +3 -1
- package/dist/providers/generated/routesRegistry.generated.js +2 -0
- package/dist/providers/runtime/antigravity/executor.js +2 -2
- package/dist/providers/runtime/antigravity/metadata.js +2 -2
- package/dist/providers/runtime/antigravity/models.js +9 -0
- package/dist/providers/runtime/antigravity/provider.js +2 -2
- package/dist/providers/runtime/antigravity/routes.js +2 -2
- package/dist/providers/runtime/antigravity/schema.js +20 -2
- package/dist/providers/runtime/antigravity/types.js +10 -2
- package/dist/providers/runtime/codebuddy/provider.js +21 -6
- package/dist/providers/runtime/gemini/provider.js +77 -0
- package/dist/providers/runtime/gemini-cli/provider.js +2 -2
- package/dist/providers/runtime/github/routes.js +1 -1
- package/dist/providers/runtime/grok/provider.js +1 -1
- package/dist/providers/runtime/kiro/executor.js +7 -4
- package/dist/providers/runtime/kiro/models.js +11 -0
- package/dist/providers/runtime/kiro/provider.js +8 -8
- package/dist/providers/runtime/minimax/routes.js +0 -1
- package/dist/providers/runtime/opencode/tools.js +39 -17
- package/dist/providers/runtime/windsurf/routes.js +0 -2
- package/dist/providers/runtime/xkiro/quota.js +4 -1
- package/dist/server/proxy/executorHelpers.js +1 -1
- package/dist/server/proxy/index.js +1 -1
- package/dist/server/proxy/pipeline.js +12 -6
- package/dist/server/proxy/proxyDispatcher.js +136 -17
- package/dist/server/proxy/responseHandlers.js +2 -18
- package/dist/server/proxy/singleModelExecutor.js +15 -3
- package/dist/server/proxy/streaming/sseStreamer.js +3 -10
- package/dist/server/routes/apiMitm.js +1 -1
- package/dist/server/routes/apiModels.js +17 -12
- package/dist/server/utils/consoleLogBuffer.js +3 -3
- package/dist/shared/constants/index.js +2 -2
- package/dist/shared/logger.js +2 -2
- package/dist/shared/utils/dnsResolver.js +69 -27
- package/dist/storage/repositories/logRepo.js +3 -23
- package/dist/storage/repositories/requestDetailsRepo.js +1 -1
- package/dist/storage/repositories/usageRepo.js +136 -74
- package/dist/web/assets/{CliToolsTab-D4DkK7Rn.js → CliToolsTab-rKSWLJC3.js} +1 -1
- package/dist/web/assets/CombosTab-D1_cfssh.js +1 -0
- package/dist/web/assets/{ConfirmModal-CuQ7ARxt.js → ConfirmModal-OWeauwYv.js} +1 -1
- package/dist/web/assets/{ConsoleLogTab-B2sfhYZW.js → ConsoleLogTab-rZe8zCb_.js} +1 -1
- package/dist/web/assets/{EditAccountModal-BusNJLvX.js → EditAccountModal-CAg-yIOn.js} +1 -1
- package/dist/web/assets/{EndpointTab-DQCezUA9.js → EndpointTab-B-Jb4wAG.js} +1 -1
- package/dist/web/assets/{MitmTab-DxEuD0DW.js → MitmTab-5dKeNi4T.js} +5 -5
- package/dist/web/assets/{ModelAutocompleteInput-CgJ2FlEf.js → ModelAutocompleteInput-CoinzdsW.js} +1 -1
- package/dist/web/assets/ProviderDetailPage-D-fodBhz.js +6 -0
- package/dist/web/assets/ProvidersTab-yzmb4w0D.js +1 -0
- package/dist/web/assets/{QuotaTab-CvXGyICr.js → QuotaTab-BXevQzen.js} +1 -1
- package/dist/web/assets/{SettingsTab-D7YF7rTP.js → SettingsTab-LkByv4Sg.js} +1 -1
- package/dist/web/assets/UsageTab-Hr8XPZD4.js +1 -0
- package/dist/web/assets/index-CKuvklEr.js +2 -0
- package/dist/web/assets/{index-BisuNW2y.css → index-HnsyZg0I.css} +1 -1
- package/dist/web/assets/metadataRegistry-NuDSSkP9.js +1 -0
- package/dist/web/assets/providers/openrouter/icon.png +0 -0
- package/dist/web/assets/providersData-DS1-ETBi.js +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +9 -1
- package/dist/web/assets/CombosTab-X1C_OmzI.js +0 -1
- package/dist/web/assets/ProviderDetailPage-DMA1DVSN.js +0 -6
- package/dist/web/assets/ProvidersTab-pZoM69s4.js +0 -1
- package/dist/web/assets/UsageTab-B0YCftIJ.js +0 -1
- package/dist/web/assets/index-DTRst7wN.js +0 -2
- package/dist/web/assets/metadataRegistry-BPZSXiBy.js +0 -1
- package/dist/web/assets/providers/openrouter/openrouter.png +0 -0
- package/dist/web/assets/providersData-Bsv7o5VV.js +0 -1
|
@@ -1,8 +1,122 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
1
2
|
import { OpenAiCompatibleProvider } from "../../core/base/openAiProvider.js";
|
|
3
|
+
import { AnthropicAdapter } from "../../../core/adapters/anthropicAdapter.js";
|
|
4
|
+
import { extractSessionId } from "../../../server/proxy/executorHelpers.js";
|
|
2
5
|
import { metadata } from "./metadata.js";
|
|
6
|
+
import { getOpenCodeGoUsage } from "./quota.js";
|
|
7
|
+
import { OPENCODE_GO_RESPONSES_URL, executeOpenCodeGoResponses, isOpenCodeGoResponsesModel, } from "./responses.js";
|
|
8
|
+
const MESSAGES_CAPABLE_PREFIXES = [
|
|
9
|
+
"claude-",
|
|
10
|
+
"deepseek-v4",
|
|
11
|
+
"minimax-m",
|
|
12
|
+
"qwen3.",
|
|
13
|
+
"space-bunny-free",
|
|
14
|
+
];
|
|
15
|
+
function stripThinkingSuffix(model) {
|
|
16
|
+
return String(model || "").replace(/\([^()]+\)\s*$/, "").trim().toLowerCase();
|
|
17
|
+
}
|
|
18
|
+
function isClaudeOnlyModel(model) {
|
|
19
|
+
return stripThinkingSuffix(model).startsWith("claude-");
|
|
20
|
+
}
|
|
21
|
+
function supportsMessagesTransport(model) {
|
|
22
|
+
const clean = stripThinkingSuffix(model);
|
|
23
|
+
return MESSAGES_CAPABLE_PREFIXES.some((prefix) => clean.startsWith(prefix));
|
|
24
|
+
}
|
|
25
|
+
function resolveOpenCodeGoSession(context) {
|
|
26
|
+
const incoming = context.req?.headers?.["x-opencode-session"];
|
|
27
|
+
if (typeof incoming === "string" && incoming.trim() && incoming.trim().length <= 256) {
|
|
28
|
+
return incoming.trim();
|
|
29
|
+
}
|
|
30
|
+
const sessionId = context.req ? extractSessionId(context.req, context.body) : context.requestId;
|
|
31
|
+
const digest = crypto
|
|
32
|
+
.createHash("sha256")
|
|
33
|
+
.update(`opencode-go\0${context.clientTool || "generic"}\0${sessionId}`)
|
|
34
|
+
.digest("hex")
|
|
35
|
+
.slice(0, 32);
|
|
36
|
+
return `ses_${digest}`;
|
|
37
|
+
}
|
|
3
38
|
export class OpencodeGoProvider extends OpenAiCompatibleProvider {
|
|
4
39
|
id = metadata.id;
|
|
5
40
|
name = metadata.name;
|
|
6
41
|
defaultFormat = metadata.format || "openai";
|
|
42
|
+
supportsQuota() {
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
async fetchQuota(context) {
|
|
46
|
+
return await getOpenCodeGoUsage(context.account.rawApiKey);
|
|
47
|
+
}
|
|
48
|
+
shouldExecute(context) {
|
|
49
|
+
return isOpenCodeGoResponsesModel(context.targetModel);
|
|
50
|
+
}
|
|
51
|
+
async execute(context) {
|
|
52
|
+
const url = this.buildUrl(context);
|
|
53
|
+
const headers = await this.buildHeaders(context);
|
|
54
|
+
return await executeOpenCodeGoResponses(context, url, headers);
|
|
55
|
+
}
|
|
56
|
+
resolveTargetFormat(targetModel, clientFormat) {
|
|
57
|
+
if (isClaudeOnlyModel(targetModel)) {
|
|
58
|
+
return "claude";
|
|
59
|
+
}
|
|
60
|
+
if (clientFormat === "anthropic" && supportsMessagesTransport(targetModel)) {
|
|
61
|
+
return "claude";
|
|
62
|
+
}
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
transformRequestBody(context) {
|
|
66
|
+
if (context.targetFormat === "claude") {
|
|
67
|
+
const modelToUse = this.resolveUpstreamModelId(context);
|
|
68
|
+
const converted = context.clientFormat === "anthropic"
|
|
69
|
+
? { ...context.body, model: modelToUse }
|
|
70
|
+
: {
|
|
71
|
+
...AnthropicAdapter.openAiToAnthropic(context.body, modelToUse || context.targetModel, context.provider?.id || this.id),
|
|
72
|
+
model: modelToUse,
|
|
73
|
+
};
|
|
74
|
+
// OpenCode Go's /messages transport uses adaptive thinking + output_config.effort for DeepSeek.
|
|
75
|
+
if (stripThinkingSuffix(context.targetModel).startsWith("deepseek") &&
|
|
76
|
+
converted?.output_config?.effort &&
|
|
77
|
+
!converted.thinking) {
|
|
78
|
+
converted.thinking = { type: "adaptive" };
|
|
79
|
+
}
|
|
80
|
+
return converted;
|
|
81
|
+
}
|
|
82
|
+
return super.transformRequestBody(context);
|
|
83
|
+
}
|
|
84
|
+
buildUrl(context) {
|
|
85
|
+
const accountBase = (context.account?.providerSpecificData?.baseUrl || "").trim();
|
|
86
|
+
const providerBase = (context.provider?.baseUrl || "").trim();
|
|
87
|
+
const customBase = accountBase || (providerBase && !providerBase.includes("opencode.ai") ? providerBase : "");
|
|
88
|
+
if (customBase) {
|
|
89
|
+
const cleanBase = customBase.replace(/\/+$/, "");
|
|
90
|
+
if (isOpenCodeGoResponsesModel(context.targetModel)) {
|
|
91
|
+
return cleanBase.endsWith("/responses") ? cleanBase : `${cleanBase}/v1/responses`;
|
|
92
|
+
}
|
|
93
|
+
if (context.targetFormat === "claude") {
|
|
94
|
+
return cleanBase.endsWith("/messages") ? cleanBase : `${cleanBase}/v1/messages`;
|
|
95
|
+
}
|
|
96
|
+
return cleanBase.endsWith("/chat/completions") ? cleanBase : `${cleanBase}/v1/chat/completions`;
|
|
97
|
+
}
|
|
98
|
+
if (isOpenCodeGoResponsesModel(context.targetModel)) {
|
|
99
|
+
return OPENCODE_GO_RESPONSES_URL;
|
|
100
|
+
}
|
|
101
|
+
if (context.targetFormat === "claude") {
|
|
102
|
+
return "https://opencode.ai/inference/go/anthropic/v1/messages";
|
|
103
|
+
}
|
|
104
|
+
return "https://opencode.ai/inference/go/openai/v1/chat/completions";
|
|
105
|
+
}
|
|
106
|
+
async buildHeaders(context) {
|
|
107
|
+
const headers = await super.buildHeaders(context);
|
|
108
|
+
headers["x-opencode-session"] = resolveOpenCodeGoSession(context);
|
|
109
|
+
if (context.targetFormat === "claude") {
|
|
110
|
+
const apiKey = (context.account?.rawApiKey || "").trim();
|
|
111
|
+
delete headers["Authorization"];
|
|
112
|
+
if (apiKey && !headers["x-api-key"]) {
|
|
113
|
+
headers["x-api-key"] = apiKey;
|
|
114
|
+
}
|
|
115
|
+
if (!headers["anthropic-version"]) {
|
|
116
|
+
headers["anthropic-version"] = "2023-06-01";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return headers;
|
|
120
|
+
}
|
|
7
121
|
}
|
|
8
122
|
export default OpencodeGoProvider;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { parseResetTime } from "../../../core/usage/utils.js";
|
|
2
|
+
import { executeUpstreamFetch } from "../../../server/proxy/proxyDispatcher.js";
|
|
3
|
+
export const OPENCODE_GO_USAGE_URL = "https://opencode.ai/inference/go/v1/usage";
|
|
4
|
+
const QUOTA_NAMES = {
|
|
5
|
+
rolling: "Rolling",
|
|
6
|
+
weekly: "Weekly",
|
|
7
|
+
monthly: "Monthly",
|
|
8
|
+
};
|
|
9
|
+
function parsePercent(value) {
|
|
10
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
11
|
+
return value;
|
|
12
|
+
if (typeof value === "string" && value.trim()) {
|
|
13
|
+
const parsed = Number(value);
|
|
14
|
+
if (Number.isFinite(parsed))
|
|
15
|
+
return parsed;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
export async function getOpenCodeGoUsage(apiKey, options) {
|
|
20
|
+
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
|
|
21
|
+
return {
|
|
22
|
+
plan: "OpenCode Go",
|
|
23
|
+
message: "OpenCode Go API key not available. Add a key to view usage.",
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const headers = {
|
|
28
|
+
Authorization: `Bearer ${apiKey.trim()}`,
|
|
29
|
+
Accept: "application/json",
|
|
30
|
+
};
|
|
31
|
+
const response = options?.fetchFn
|
|
32
|
+
? await options.fetchFn(OPENCODE_GO_USAGE_URL, {
|
|
33
|
+
method: "GET",
|
|
34
|
+
headers,
|
|
35
|
+
signal: AbortSignal.timeout(8000),
|
|
36
|
+
})
|
|
37
|
+
: await executeUpstreamFetch(OPENCODE_GO_USAGE_URL, {
|
|
38
|
+
method: "GET",
|
|
39
|
+
headers,
|
|
40
|
+
signal: AbortSignal.timeout(8000),
|
|
41
|
+
}, options?.proxyUrl);
|
|
42
|
+
if (response.status === 401) {
|
|
43
|
+
return {
|
|
44
|
+
plan: "OpenCode Go",
|
|
45
|
+
message: "OpenCode Go authentication failed. Check the API key.",
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (response.status === 403) {
|
|
49
|
+
const err = await response.json().catch(() => null);
|
|
50
|
+
const subscriptionRequired = err?.error?.type === "EntitlementError";
|
|
51
|
+
return {
|
|
52
|
+
plan: "OpenCode Go",
|
|
53
|
+
message: subscriptionRequired
|
|
54
|
+
? "OpenCode Go subscription required for this API key."
|
|
55
|
+
: "OpenCode Go access forbidden for this API key.",
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
return {
|
|
60
|
+
plan: "OpenCode Go",
|
|
61
|
+
message: `OpenCode Go usage API error (${response.status}).`,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const data = await response.json().catch(() => null);
|
|
65
|
+
if (!data?.usage || typeof data.usage !== "object") {
|
|
66
|
+
return {
|
|
67
|
+
plan: "OpenCode Go",
|
|
68
|
+
message: "OpenCode Go usage response did not contain quota data.",
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const quotas = {};
|
|
72
|
+
for (const [period, name] of Object.entries(QUOTA_NAMES)) {
|
|
73
|
+
const quota = data.usage[period];
|
|
74
|
+
if (!quota || typeof quota !== "object")
|
|
75
|
+
continue;
|
|
76
|
+
const percent = parsePercent(quota.percent);
|
|
77
|
+
if (percent === null)
|
|
78
|
+
continue;
|
|
79
|
+
const used = Math.max(0, Math.min(100, percent));
|
|
80
|
+
const remaining = Math.max(0, 100 - used);
|
|
81
|
+
quotas[name] = {
|
|
82
|
+
displayName: name,
|
|
83
|
+
used,
|
|
84
|
+
total: 100,
|
|
85
|
+
remaining,
|
|
86
|
+
remainingPercentage: remaining,
|
|
87
|
+
resetAt: parseResetTime(quota.resetsAt),
|
|
88
|
+
unlimited: false,
|
|
89
|
+
recurring: true,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
if (Object.keys(quotas).length === 0) {
|
|
93
|
+
return {
|
|
94
|
+
plan: "OpenCode Go",
|
|
95
|
+
message: "OpenCode Go usage response did not contain valid quota data.",
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
return { plan: "OpenCode Go", quotas };
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
return {
|
|
102
|
+
plan: "OpenCode Go",
|
|
103
|
+
message: `OpenCode Go error: ${error?.message || String(error)}`,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { AnthropicAdapter } from "../../../core/adapters/anthropicAdapter.js";
|
|
2
|
+
import { executeUpstreamFetch } from "../../../server/proxy/proxyDispatcher.js";
|
|
3
|
+
import { ResponseLogger } from "../../../server/proxy/responseLogger.js";
|
|
4
|
+
import { SettingsRepository } from "../../../storage/repositories/settingsRepo.js";
|
|
5
|
+
import { logger, LogSymbol, formatDoneLine } from "../../../shared/logger.js";
|
|
6
|
+
import { OPENCODE_GO_RESPONSES_URL, isOpenCodeGoResponsesModel, buildOpenCodeGoResponsesPayload, } from "./responsesPayload.js";
|
|
7
|
+
export { OPENCODE_GO_RESPONSES_URL, isOpenCodeGoResponsesModel, buildOpenCodeGoResponsesPayload };
|
|
8
|
+
function recordResponsesSuccess(context, targetModel, usage, fullText, clientResponse) {
|
|
9
|
+
const { req, startTime, requestId, reqTag = "OCG" } = context;
|
|
10
|
+
const durationMs = Date.now() - startTime;
|
|
11
|
+
const inTok = usage?.prompt_tokens || context.rtkStats?.compressedTokens || 0;
|
|
12
|
+
const outTok = usage?.completion_tokens || Math.ceil(fullText.length / 4);
|
|
13
|
+
const calculatedCost = ResponseLogger.logSuccess({
|
|
14
|
+
requestId,
|
|
15
|
+
startTime,
|
|
16
|
+
durationMs,
|
|
17
|
+
clientTool: context.clientTool || "generic",
|
|
18
|
+
rawModel: context.rawModel || targetModel,
|
|
19
|
+
targetModel,
|
|
20
|
+
providerId: "opencode-go",
|
|
21
|
+
accountId: context.account?.id,
|
|
22
|
+
accountName: context.account?.name,
|
|
23
|
+
apiKeyId: context.apiKeyId,
|
|
24
|
+
apiKeyName: context.apiKeyName,
|
|
25
|
+
promptTokens: inTok,
|
|
26
|
+
completionTokens: outTok,
|
|
27
|
+
cachedTokens: 0,
|
|
28
|
+
cacheCreationTokens: 0,
|
|
29
|
+
reasoningTokens: 0,
|
|
30
|
+
tokensSavedByRtk: context.rtkStats?.tokensSaved || 0,
|
|
31
|
+
is1mContext: context.is1mContext,
|
|
32
|
+
requestHeaders: req?.headers || {},
|
|
33
|
+
requestBody: req?.body,
|
|
34
|
+
clientResponse,
|
|
35
|
+
});
|
|
36
|
+
const doneMsg = formatDoneLine({
|
|
37
|
+
durationMs,
|
|
38
|
+
promptTokens: inTok,
|
|
39
|
+
completionTokens: outTok,
|
|
40
|
+
tokensSaved: context.rtkStats?.tokensSaved || 0,
|
|
41
|
+
cost: calculatedCost,
|
|
42
|
+
});
|
|
43
|
+
logger.line(reqTag, LogSymbol.SUCCESS, `opencode-go/${targetModel} · ${doneMsg}`);
|
|
44
|
+
}
|
|
45
|
+
export async function executeOpenCodeGoResponses(context, targetUrl, baseHeaders) {
|
|
46
|
+
const { req, res, clientFormat, isPanel, requestId, targetModel } = context;
|
|
47
|
+
if (!res)
|
|
48
|
+
return { ok: false, status: 500, error: "Response object is required" };
|
|
49
|
+
const globalSettings = SettingsRepository.getEndpointSettings();
|
|
50
|
+
const headers = { ...baseHeaders };
|
|
51
|
+
if (globalSettings.customHeaders) {
|
|
52
|
+
for (const [k, v] of Object.entries(globalSettings.customHeaders)) {
|
|
53
|
+
if (!headers[k])
|
|
54
|
+
headers[k] = v;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const proxyUrl = (context.provider?.proxyUrl || "").trim() || (globalSettings.proxyUrl || "").trim();
|
|
58
|
+
const rawBody = context.body || req?.body || {};
|
|
59
|
+
const isStreaming = rawBody.stream !== false && !isPanel;
|
|
60
|
+
const payload = buildOpenCodeGoResponsesPayload(rawBody, targetModel, clientFormat);
|
|
61
|
+
const abortController = new AbortController();
|
|
62
|
+
const onClose = () => abortController.abort();
|
|
63
|
+
if (typeof res?.once === "function")
|
|
64
|
+
res.once("close", onClose);
|
|
65
|
+
try {
|
|
66
|
+
const upstreamRes = await executeUpstreamFetch(targetUrl, { method: "POST", headers, body: JSON.stringify(payload), signal: abortController.signal }, proxyUrl);
|
|
67
|
+
if (!upstreamRes.ok) {
|
|
68
|
+
const errText = await upstreamRes.text().catch(() => "");
|
|
69
|
+
return { ok: false, status: upstreamRes.status, error: errText || `OpenCode Go responses failed (${upstreamRes.status})` };
|
|
70
|
+
}
|
|
71
|
+
const reader = upstreamRes.body?.getReader();
|
|
72
|
+
if (!reader)
|
|
73
|
+
return { ok: false, status: 502, error: "Empty response stream from OpenCode Go" };
|
|
74
|
+
const decoder = new TextDecoder();
|
|
75
|
+
const responseId = `chatcmpl-${requestId}`;
|
|
76
|
+
const created = Math.floor(Date.now() / 1000);
|
|
77
|
+
const anthropicState = isStreaming && clientFormat === "anthropic"
|
|
78
|
+
? AnthropicAdapter.createStreamState(`msg_${requestId}`, rawBody.tools)
|
|
79
|
+
: undefined;
|
|
80
|
+
let headersSent = false;
|
|
81
|
+
const ensureSseHeaders = () => {
|
|
82
|
+
if (headersSent || res.writableEnded || res.destroyed)
|
|
83
|
+
return;
|
|
84
|
+
headersSent = true;
|
|
85
|
+
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
|
86
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
87
|
+
res.setHeader("Connection", "keep-alive");
|
|
88
|
+
res.flushHeaders?.();
|
|
89
|
+
if (clientFormat === "anthropic" && anthropicState && !anthropicState.messageStartSent) {
|
|
90
|
+
anthropicState.messageStartSent = true;
|
|
91
|
+
res.write(`event: message_start\ndata: ${JSON.stringify({
|
|
92
|
+
type: "message_start",
|
|
93
|
+
message: { id: `msg_${requestId}`, type: "message", role: "assistant", model: targetModel, content: [] },
|
|
94
|
+
})}\n\n`);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const emitOpenAiChunk = (chunk) => {
|
|
98
|
+
if (!isStreaming || res.writableEnded || res.destroyed)
|
|
99
|
+
return;
|
|
100
|
+
ensureSseHeaders();
|
|
101
|
+
if (clientFormat === "anthropic" && anthropicState) {
|
|
102
|
+
for (const ev of AnthropicAdapter.openAiChunkToAnthropicEvent(chunk, `msg_${requestId}`, anthropicState)) {
|
|
103
|
+
res.write(ev);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
let buffer = "";
|
|
111
|
+
let fullText = "";
|
|
112
|
+
let reasoningText = "";
|
|
113
|
+
let sentRole = false;
|
|
114
|
+
let toolIdx = 0;
|
|
115
|
+
const toolIndexByItemId = new Map();
|
|
116
|
+
const toolMetaByItemId = new Map();
|
|
117
|
+
let completedResponse = null;
|
|
118
|
+
let usage = undefined;
|
|
119
|
+
let upstreamError = null;
|
|
120
|
+
const handleEvent = (ev) => {
|
|
121
|
+
const t = ev?.type;
|
|
122
|
+
if (!t)
|
|
123
|
+
return;
|
|
124
|
+
if (t === "response.failed" || t === "error") {
|
|
125
|
+
const errObj = ev.response?.error || ev.error || ev;
|
|
126
|
+
const message = errObj?.message || (typeof errObj === "string" ? errObj : "OpenCode Go response failed");
|
|
127
|
+
const status = Number(errObj?.status || errObj?.statusCode || 502) || 502;
|
|
128
|
+
upstreamError = { status, message };
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (t === "response.output_text.delta" && typeof ev.delta === "string") {
|
|
132
|
+
fullText += ev.delta;
|
|
133
|
+
const delta = { content: ev.delta };
|
|
134
|
+
if (!sentRole) {
|
|
135
|
+
delta.role = "assistant";
|
|
136
|
+
sentRole = true;
|
|
137
|
+
}
|
|
138
|
+
emitOpenAiChunk({ id: responseId, object: "chat.completion.chunk", created, model: targetModel, choices: [{ index: 0, delta, finish_reason: null }] });
|
|
139
|
+
}
|
|
140
|
+
else if (t === "response.reasoning_summary_text.delta" && typeof ev.delta === "string") {
|
|
141
|
+
reasoningText += ev.delta;
|
|
142
|
+
const delta = { reasoning_content: ev.delta };
|
|
143
|
+
if (!sentRole) {
|
|
144
|
+
delta.role = "assistant";
|
|
145
|
+
sentRole = true;
|
|
146
|
+
}
|
|
147
|
+
emitOpenAiChunk({ id: responseId, object: "chat.completion.chunk", created, model: targetModel, choices: [{ index: 0, delta, finish_reason: null }] });
|
|
148
|
+
}
|
|
149
|
+
else if (t === "response.output_item.added" && ev.item?.type === "function_call") {
|
|
150
|
+
const itemId = ev.item.id || `item_${toolIdx}`;
|
|
151
|
+
const callId = ev.item.call_id || itemId;
|
|
152
|
+
const name = ev.item.name || "";
|
|
153
|
+
const idx = toolIndexByItemId.has(itemId) ? toolIndexByItemId.get(itemId) : toolIdx++;
|
|
154
|
+
toolIndexByItemId.set(itemId, idx);
|
|
155
|
+
toolMetaByItemId.set(itemId, { id: callId, name, args: "" });
|
|
156
|
+
const delta = { tool_calls: [{ index: idx, id: callId, type: "function", function: { name, arguments: "" } }] };
|
|
157
|
+
if (!sentRole) {
|
|
158
|
+
delta.role = "assistant";
|
|
159
|
+
sentRole = true;
|
|
160
|
+
}
|
|
161
|
+
emitOpenAiChunk({ id: responseId, object: "chat.completion.chunk", created, model: targetModel, choices: [{ index: 0, delta, finish_reason: null }] });
|
|
162
|
+
}
|
|
163
|
+
else if (t === "response.function_call_arguments.delta" && typeof ev.delta === "string") {
|
|
164
|
+
const idx = toolIndexByItemId.get(ev.item_id);
|
|
165
|
+
if (idx !== undefined) {
|
|
166
|
+
const meta = toolMetaByItemId.get(ev.item_id);
|
|
167
|
+
if (meta)
|
|
168
|
+
meta.args += ev.delta;
|
|
169
|
+
emitOpenAiChunk({
|
|
170
|
+
id: responseId,
|
|
171
|
+
object: "chat.completion.chunk",
|
|
172
|
+
created,
|
|
173
|
+
model: targetModel,
|
|
174
|
+
choices: [{ index: 0, delta: { tool_calls: [{ index: idx, function: { arguments: ev.delta } }] }, finish_reason: null }],
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else if (t === "response.completed") {
|
|
179
|
+
completedResponse = ev.response || ev;
|
|
180
|
+
const u = completedResponse?.usage;
|
|
181
|
+
if (u) {
|
|
182
|
+
const inTok = u.input_tokens ?? 0;
|
|
183
|
+
const outTok = u.output_tokens ?? 0;
|
|
184
|
+
usage = { prompt_tokens: inTok, completion_tokens: outTok, total_tokens: inTok + outTok };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
const processLine = (rawLine) => {
|
|
189
|
+
const line = rawLine.trim();
|
|
190
|
+
if (!line.startsWith("data:"))
|
|
191
|
+
return;
|
|
192
|
+
const dataStr = line.slice(5).trim();
|
|
193
|
+
if (!dataStr || dataStr === "[DONE]")
|
|
194
|
+
return;
|
|
195
|
+
try {
|
|
196
|
+
handleEvent(JSON.parse(dataStr));
|
|
197
|
+
}
|
|
198
|
+
catch { }
|
|
199
|
+
};
|
|
200
|
+
while (true) {
|
|
201
|
+
const { done, value } = await reader.read();
|
|
202
|
+
if (done)
|
|
203
|
+
break;
|
|
204
|
+
const chunkStr = decoder.decode(value, { stream: true });
|
|
205
|
+
buffer += chunkStr;
|
|
206
|
+
const lines = buffer.split("\n");
|
|
207
|
+
buffer = lines.pop() || "";
|
|
208
|
+
for (const rawLine of lines)
|
|
209
|
+
processLine(rawLine);
|
|
210
|
+
if (upstreamError)
|
|
211
|
+
break;
|
|
212
|
+
if (isStreaming && clientFormat === "responses") {
|
|
213
|
+
ensureSseHeaders();
|
|
214
|
+
if (!res.writableEnded && !res.destroyed)
|
|
215
|
+
res.write(chunkStr);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (!upstreamError && buffer.trim())
|
|
219
|
+
processLine(buffer);
|
|
220
|
+
if (upstreamError) {
|
|
221
|
+
const err = upstreamError;
|
|
222
|
+
if (headersSent && !res.writableEnded && !res.destroyed)
|
|
223
|
+
res.end();
|
|
224
|
+
return { ok: false, status: err.status, error: err.message };
|
|
225
|
+
}
|
|
226
|
+
if (isStreaming) {
|
|
227
|
+
if (clientFormat === "responses") {
|
|
228
|
+
if (!res.writableEnded && !res.destroyed)
|
|
229
|
+
res.end();
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
const finishReason = toolMetaByItemId.size > 0 ? "tool_calls" : "stop";
|
|
233
|
+
emitOpenAiChunk({
|
|
234
|
+
id: responseId,
|
|
235
|
+
object: "chat.completion.chunk",
|
|
236
|
+
created,
|
|
237
|
+
model: targetModel,
|
|
238
|
+
choices: [{ index: 0, delta: {}, finish_reason: finishReason }],
|
|
239
|
+
...(usage ? { usage } : {}),
|
|
240
|
+
});
|
|
241
|
+
if (!res.writableEnded && !res.destroyed) {
|
|
242
|
+
if (clientFormat === "anthropic" && anthropicState) {
|
|
243
|
+
for (const ev of AnthropicAdapter.finalizeStream(anthropicState))
|
|
244
|
+
res.write(ev);
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
res.write("data: [DONE]\n\n");
|
|
248
|
+
}
|
|
249
|
+
res.end();
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
recordResponsesSuccess(context, targetModel, usage, fullText, {
|
|
253
|
+
status: 200,
|
|
254
|
+
headers: { "content-type": "text/event-stream" },
|
|
255
|
+
body: { text: "Stream completed" },
|
|
256
|
+
});
|
|
257
|
+
return { ok: true, status: 200, logged: true, modelUsed: targetModel, text: fullText };
|
|
258
|
+
}
|
|
259
|
+
const toolCalls = Array.from(toolMetaByItemId.values()).map((tc) => ({
|
|
260
|
+
id: tc.id,
|
|
261
|
+
type: "function",
|
|
262
|
+
function: { name: tc.name, arguments: tc.args || "{}" },
|
|
263
|
+
}));
|
|
264
|
+
const openAiResp = {
|
|
265
|
+
id: responseId,
|
|
266
|
+
object: "chat.completion",
|
|
267
|
+
created,
|
|
268
|
+
model: targetModel,
|
|
269
|
+
choices: [{
|
|
270
|
+
index: 0,
|
|
271
|
+
message: {
|
|
272
|
+
role: "assistant",
|
|
273
|
+
content: fullText || null,
|
|
274
|
+
...(reasoningText ? { reasoning_content: reasoningText } : {}),
|
|
275
|
+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
276
|
+
},
|
|
277
|
+
finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop",
|
|
278
|
+
}],
|
|
279
|
+
...(usage ? { usage } : {}),
|
|
280
|
+
};
|
|
281
|
+
if (isPanel) {
|
|
282
|
+
return { ok: true, status: 200, json: openAiResp, text: fullText, logged: false, modelUsed: targetModel };
|
|
283
|
+
}
|
|
284
|
+
const outBody = clientFormat === "responses" && completedResponse
|
|
285
|
+
? completedResponse
|
|
286
|
+
: clientFormat === "anthropic"
|
|
287
|
+
? AnthropicAdapter.openAiResponseToAnthropic(openAiResp)
|
|
288
|
+
: openAiResp;
|
|
289
|
+
res.status(200).json(outBody);
|
|
290
|
+
recordResponsesSuccess(context, targetModel, usage, fullText, {
|
|
291
|
+
status: 200,
|
|
292
|
+
headers: { "content-type": "application/json" },
|
|
293
|
+
body: outBody,
|
|
294
|
+
});
|
|
295
|
+
return { ok: true, status: 200, json: outBody, text: fullText, logged: true, modelUsed: targetModel };
|
|
296
|
+
}
|
|
297
|
+
finally {
|
|
298
|
+
if (typeof res?.removeListener === "function")
|
|
299
|
+
res.removeListener("close", onClose);
|
|
300
|
+
}
|
|
301
|
+
}
|