mapigate 0.5.130 → 0.5.136

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 (56) hide show
  1. package/README.md +1 -1
  2. package/dist/core/adapters/anthropic/requestAnthropicToOpenAi.js +59 -11
  3. package/dist/core/adapters/anthropicAdapter.js +2 -2
  4. package/dist/providers/catalog/commandcode/converter.js +215 -0
  5. package/dist/providers/catalog/commandcode/executor.js +305 -0
  6. package/dist/providers/catalog/commandcode/headers.js +76 -0
  7. package/dist/providers/catalog/commandcode/metadata.js +4 -1
  8. package/dist/providers/catalog/commandcode/ndjson.js +161 -0
  9. package/dist/providers/catalog/commandcode/provider.js +18 -35
  10. package/dist/providers/catalog/commandcode/routes.js +75 -0
  11. package/dist/providers/catalog/opencode-go/metadata.js +4 -2
  12. package/dist/providers/catalog/opencode-go/models.js +1 -0
  13. package/dist/providers/catalog/opencode-go/provider.js +114 -0
  14. package/dist/providers/catalog/opencode-go/quota.js +106 -0
  15. package/dist/providers/catalog/opencode-go/responses.js +301 -0
  16. package/dist/providers/catalog/opencode-go/responsesPayload.js +228 -0
  17. package/dist/providers/catalog/sensenova/metadata.js +35 -0
  18. package/dist/providers/core/base/baseProvider.js +3 -0
  19. package/dist/providers/core/base/openAiProvider.js +3 -1
  20. package/dist/providers/generated/routesRegistry.generated.js +2 -0
  21. package/dist/providers/runtime/antigravity/schema.js +19 -1
  22. package/dist/providers/runtime/codebuddy/provider.js +21 -6
  23. package/dist/providers/runtime/kiro/converter.js +2 -1
  24. package/dist/providers/runtime/kiro/executor.js +15 -9
  25. package/dist/providers/runtime/kiro/metadata.js +3 -3
  26. package/dist/providers/runtime/kiro/models.js +11 -0
  27. package/dist/providers/runtime/kiro/provider.js +12 -8
  28. package/dist/providers/runtime/kiro/quota.js +4 -4
  29. package/dist/providers/runtime/opencode/tools.js +38 -16
  30. package/dist/server/proxy/proxyDispatcher.js +136 -17
  31. package/dist/server/proxy/singleModelExecutor.js +14 -2
  32. package/dist/server/routes/apiModels.js +15 -6
  33. package/dist/shared/utils/dnsResolver.js +69 -27
  34. package/dist/web/assets/{CliToolsTab-Ck8EuOcF.js → CliToolsTab-CkzwuwaC.js} +1 -1
  35. package/dist/web/assets/CombosTab-C5RzRwwr.js +1 -0
  36. package/dist/web/assets/{ConfirmModal-1KqBoeRh.js → ConfirmModal-DGvcf0gB.js} +1 -1
  37. package/dist/web/assets/{ConsoleLogTab-DC2FAcl1.js → ConsoleLogTab-84Ens8T5.js} +1 -1
  38. package/dist/web/assets/{EditAccountModal-1EbG3eyM.js → EditAccountModal-D-_omvev.js} +1 -1
  39. package/dist/web/assets/{EndpointTab-C-gwVRmb.js → EndpointTab-7nBfEdYE.js} +1 -1
  40. package/dist/web/assets/{MitmTab-C2kTKbAV.js → MitmTab-CqS6mXHZ.js} +1 -1
  41. package/dist/web/assets/{ModelAutocompleteInput-K8-vMnIb.js → ModelAutocompleteInput-B9syrV1O.js} +1 -1
  42. package/dist/web/assets/ProviderDetailPage-DGZceQ2d.js +6 -0
  43. package/dist/web/assets/{ProvidersTab-w9OOjPmA.js → ProvidersTab-CiYbqRou.js} +1 -1
  44. package/dist/web/assets/{QuotaTab-C43xP8JP.js → QuotaTab-DFr0DWAU.js} +1 -1
  45. package/dist/web/assets/{SettingsTab-BMs0BtId.js → SettingsTab-4c0ksNJa.js} +1 -1
  46. package/dist/web/assets/{UsageTab-C5MbpcRp.js → UsageTab-BQcPmvtQ.js} +1 -1
  47. package/dist/web/assets/{index-DVeDwPjn.js → index-C4NTQZ40.js} +2 -2
  48. package/dist/web/assets/{index-BisuNW2y.css → index-HnsyZg0I.css} +1 -1
  49. package/dist/web/assets/metadataRegistry-B91sal4r.js +1 -0
  50. package/dist/web/assets/providersData-DkVCRBsJ.js +1 -0
  51. package/dist/web/index.html +2 -2
  52. package/package.json +1 -1
  53. package/dist/web/assets/CombosTab-CLPru5aK.js +0 -1
  54. package/dist/web/assets/ProviderDetailPage-BSqwg2fW.js +0 -6
  55. package/dist/web/assets/metadataRegistry-BMKXREeE.js +0 -1
  56. package/dist/web/assets/providersData-D7kilpPx.js +0 -1
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
14
14
  [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS-blueviolet.svg)](#)
15
15
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
16
- [![Version](https://img.shields.io/badge/version-0.5.130-orange.svg)](package.json)
16
+ [![Version](https://img.shields.io/badge/version-0.5.136-orange.svg)](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
 
@@ -2,17 +2,46 @@ import { convertAnthropicImageToOpenAi } from "./imageUtils.js";
2
2
  /**
3
3
  * Translates Anthropic /v1/messages request payload to OpenAI /v1/chat/completions payload
4
4
  */
5
- export function translateAnthropicToOpenAi(anthropicBody) {
5
+ export function translateAnthropicToOpenAi(anthropicBody, opts = {}) {
6
+ const preserveCacheControl = Boolean(opts?.preserveCacheControl);
6
7
  const messages = [];
7
8
  // 1. Top-level system prompt
8
9
  if (anthropicBody.system) {
9
- const sysContent = typeof anthropicBody.system === "string"
10
- ? anthropicBody.system
11
- : Array.isArray(anthropicBody.system)
12
- ? anthropicBody.system.map((s) => s.text || "").join("\n")
13
- : "";
14
- if (sysContent) {
15
- messages.push({ role: "system", content: sysContent });
10
+ if (preserveCacheControl &&
11
+ Array.isArray(anthropicBody.system) &&
12
+ anthropicBody.system.some((s) => s?.cache_control)) {
13
+ const systemParts = [];
14
+ for (const s of anthropicBody.system) {
15
+ const text = s?.text || "";
16
+ if (text) {
17
+ systemParts.push({
18
+ type: "text",
19
+ text,
20
+ ...(s.cache_control ? { cache_control: s.cache_control } : {}),
21
+ });
22
+ }
23
+ else if (s?.cache_control && systemParts.length > 0) {
24
+ systemParts[systemParts.length - 1].cache_control = s.cache_control;
25
+ }
26
+ }
27
+ if (systemParts.length > 0) {
28
+ const content = systemParts.some((p) => p.cache_control)
29
+ ? systemParts
30
+ : systemParts.map((p) => p.text).join("\n");
31
+ if (Array.isArray(content) ? content.length > 0 : content) {
32
+ messages.push({ role: "system", content });
33
+ }
34
+ }
35
+ }
36
+ else {
37
+ const sysContent = typeof anthropicBody.system === "string"
38
+ ? anthropicBody.system
39
+ : Array.isArray(anthropicBody.system)
40
+ ? anthropicBody.system.map((s) => s.text || "").join("\n")
41
+ : "";
42
+ if (sysContent) {
43
+ messages.push({ role: "system", content: sysContent });
44
+ }
16
45
  }
17
46
  }
18
47
  // 2. Messages array
@@ -33,6 +62,8 @@ export function translateAnthropicToOpenAi(anthropicBody) {
33
62
  }
34
63
  if (Array.isArray(msg.content)) {
35
64
  let textAccumulator = "";
65
+ const textBlocks = [];
66
+ let hasTextCacheControl = false;
36
67
  let reasoningAccumulator = "";
37
68
  let thinkingSignature = undefined;
38
69
  let redactedThinking = undefined;
@@ -41,6 +72,18 @@ export function translateAnthropicToOpenAi(anthropicBody) {
41
72
  for (const block of msg.content) {
42
73
  if (block.type === "text") {
43
74
  textAccumulator += (block.text || "") + "\n";
75
+ if (preserveCacheControl && block.cache_control) {
76
+ hasTextCacheControl = true;
77
+ }
78
+ if (block.text) {
79
+ textBlocks.push({
80
+ type: "text",
81
+ text: block.text,
82
+ ...(preserveCacheControl && block.cache_control
83
+ ? { cache_control: block.cache_control }
84
+ : {}),
85
+ });
86
+ }
44
87
  }
45
88
  else if (block.type === "thinking") {
46
89
  if (block.thinking) {
@@ -111,12 +154,17 @@ export function translateAnthropicToOpenAi(anthropicBody) {
111
154
  const hasImages = imageBlocks.length > 0;
112
155
  if (hasText || hasReasoning || hasToolCalls || redactedThinking || hasImages) {
113
156
  let finalContent = textAccumulator.trim() || null;
114
- if (hasImages) {
157
+ if (hasImages || (preserveCacheControl && hasTextCacheControl && textBlocks.length > 0)) {
115
158
  finalContent = [];
116
- if (textAccumulator.trim()) {
159
+ if (preserveCacheControl && hasTextCacheControl && textBlocks.length > 0) {
160
+ finalContent.push(...textBlocks);
161
+ }
162
+ else if (textAccumulator.trim()) {
117
163
  finalContent.push({ type: "text", text: textAccumulator.trim() });
118
164
  }
119
- finalContent.push(...imageBlocks);
165
+ if (hasImages) {
166
+ finalContent.push(...imageBlocks);
167
+ }
120
168
  }
121
169
  const outMsg = { role, content: finalContent };
122
170
  if (hasReasoning) {
@@ -29,8 +29,8 @@ export class AnthropicAdapter {
29
29
  /**
30
30
  * Convert Anthropic /v1/messages payload to OpenAI /v1/chat/completions payload
31
31
  */
32
- static anthropicToOpenAi(anthropicBody) {
33
- return translateAnthropicToOpenAi(anthropicBody);
32
+ static anthropicToOpenAi(anthropicBody, opts) {
33
+ return translateAnthropicToOpenAi(anthropicBody, opts);
34
34
  }
35
35
  /**
36
36
  * Convert OpenAI /v1/chat/completions payload to Anthropic /v1/messages payload
@@ -0,0 +1,215 @@
1
+ import { COMMAND_CODE_WORKING_DIR, toCommandCodeSessionUuid } from "./headers.js";
2
+ export { CommandCodeUpstreamError, createCommandCodeStreamState, parseCommandCodeError, commandCodeLineToOpenAiChunks, } from "./ndjson.js";
3
+ const COMMAND_CODE_MAX_TOKENS = 64000;
4
+ function flattenText(content) {
5
+ if (content == null)
6
+ return "";
7
+ if (typeof content === "string")
8
+ return content;
9
+ if (Array.isArray(content)) {
10
+ const parts = [];
11
+ for (const p of content) {
12
+ if (typeof p === "string")
13
+ parts.push(p);
14
+ else if (p && typeof p === "object" && typeof p.text === "string")
15
+ parts.push(p.text);
16
+ }
17
+ return parts.join("\n");
18
+ }
19
+ return String(content);
20
+ }
21
+ function toNativeImageBlock(part) {
22
+ if (!part || typeof part !== "object")
23
+ return null;
24
+ if (part.type === "image_url") {
25
+ const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url;
26
+ if (typeof url !== "string" || !url.startsWith("data:"))
27
+ return null;
28
+ const match = url.match(/^data:([^;]+);base64,(.+)$/s);
29
+ if (!match)
30
+ return null;
31
+ return { type: "image", image: url, mimeType: match[1], mediaType: match[1] };
32
+ }
33
+ if (part.type === "image") {
34
+ if (typeof part.image === "string" && part.image.startsWith("data:")) {
35
+ const match = part.image.match(/^data:([^;]+);base64,/);
36
+ const mime = part.mimeType || match?.[1] || "image/png";
37
+ return { type: "image", image: part.image, mimeType: mime, mediaType: mime };
38
+ }
39
+ if (part.source?.type === "base64" && typeof part.source.data === "string") {
40
+ const mime = part.source.media_type || "image/png";
41
+ return {
42
+ type: "image",
43
+ image: `data:${mime};base64,${part.source.data}`,
44
+ mimeType: mime,
45
+ mediaType: mime,
46
+ };
47
+ }
48
+ }
49
+ return null;
50
+ }
51
+ function toContentBlocks(content) {
52
+ if (content == null)
53
+ return [{ type: "text", text: "" }];
54
+ if (typeof content === "string")
55
+ return [{ type: "text", text: content }];
56
+ if (Array.isArray(content)) {
57
+ const blocks = [];
58
+ for (const part of content) {
59
+ if (typeof part === "string") {
60
+ blocks.push({ type: "text", text: part });
61
+ }
62
+ else if (part && typeof part === "object") {
63
+ if (part.type === "text" && typeof part.text === "string") {
64
+ blocks.push({ type: "text", text: part.text });
65
+ }
66
+ else {
67
+ const img = toNativeImageBlock(part);
68
+ if (img)
69
+ blocks.push(img);
70
+ else if (typeof part.text === "string")
71
+ blocks.push({ type: "text", text: part.text });
72
+ }
73
+ }
74
+ }
75
+ return blocks.length ? blocks : [{ type: "text", text: "" }];
76
+ }
77
+ return [{ type: "text", text: String(content) }];
78
+ }
79
+ function safeParseJson(s) {
80
+ if (s == null)
81
+ return {};
82
+ if (typeof s !== "string")
83
+ return s;
84
+ const trimmed = s.trim();
85
+ if (!trimmed)
86
+ return {};
87
+ try {
88
+ const parsed = JSON.parse(trimmed);
89
+ return parsed && typeof parsed === "object" ? parsed : { value: parsed };
90
+ }
91
+ catch {
92
+ return { raw: s };
93
+ }
94
+ }
95
+ export function buildCommandCodePayload(model, body, sessionId) {
96
+ const sourceMessages = Array.isArray(body?.messages) ? body.messages : [];
97
+ const out = [];
98
+ const systemTexts = [];
99
+ const toolCallIdToName = new Map();
100
+ for (const m of sourceMessages) {
101
+ if (m?.role === "assistant" && Array.isArray(m.tool_calls)) {
102
+ for (const tc of m.tool_calls) {
103
+ const name = tc?.function?.name || tc?.name;
104
+ if (tc?.id && name)
105
+ toolCallIdToName.set(tc.id, name);
106
+ }
107
+ }
108
+ }
109
+ for (const m of sourceMessages) {
110
+ if (!m)
111
+ continue;
112
+ if (m.role === "system" || m.role === "developer") {
113
+ const t = flattenText(m.content);
114
+ if (t)
115
+ systemTexts.push(t);
116
+ continue;
117
+ }
118
+ if (m.role === "tool") {
119
+ const value = typeof m.content === "string" ? m.content : flattenText(m.content);
120
+ const isError = Boolean(m.is_error || m.status === "error");
121
+ const toolName = m.name || (m.tool_call_id ? toolCallIdToName.get(m.tool_call_id) : null) || "unknown";
122
+ out.push({
123
+ role: "tool",
124
+ content: [{
125
+ type: "tool-result",
126
+ toolCallId: m.tool_call_id || "",
127
+ toolName,
128
+ output: { type: isError ? "error-text" : "text", value },
129
+ }],
130
+ });
131
+ continue;
132
+ }
133
+ if (m.role === "assistant") {
134
+ const blocks = [];
135
+ const rc = m.reasoning_content || m.thought || m.reasoning;
136
+ if (rc && typeof rc === "string" && rc.trim()) {
137
+ blocks.push({ type: "reasoning", text: rc });
138
+ }
139
+ const text = flattenText(m.content);
140
+ if (text)
141
+ blocks.push({ type: "text", text });
142
+ if (Array.isArray(m.tool_calls)) {
143
+ for (const tc of m.tool_calls) {
144
+ const fn = tc.function || {};
145
+ blocks.push({
146
+ type: "tool-call",
147
+ toolCallId: tc.id || "",
148
+ toolName: fn.name || tc.name || "",
149
+ input: safeParseJson(fn.arguments ?? tc.input),
150
+ });
151
+ }
152
+ }
153
+ out.push({ role: "assistant", content: blocks.length ? blocks : [{ type: "text", text: "" }] });
154
+ continue;
155
+ }
156
+ out.push({ role: "user", content: toContentBlocks(m.content) });
157
+ }
158
+ const tools = Array.isArray(body?.tools)
159
+ ? body.tools
160
+ .map((t) => {
161
+ if (!t)
162
+ return null;
163
+ if (t.type === "function" && t.function) {
164
+ return {
165
+ name: t.function.name,
166
+ description: t.function.description,
167
+ input_schema: t.function.parameters || { type: "object" },
168
+ };
169
+ }
170
+ if (t.name && (t.input_schema || t.parameters)) {
171
+ return { name: t.name, description: t.description, input_schema: t.input_schema || t.parameters };
172
+ }
173
+ return null;
174
+ })
175
+ .filter(Boolean)
176
+ : undefined;
177
+ const params = {
178
+ model,
179
+ messages: out,
180
+ stream: true,
181
+ max_tokens: body?.max_tokens ?? body?.max_output_tokens ?? COMMAND_CODE_MAX_TOKENS,
182
+ temperature: body?.temperature ?? 0.3,
183
+ };
184
+ if (systemTexts.length > 0)
185
+ params.system = systemTexts.join("\n\n");
186
+ if (tools && tools.length > 0)
187
+ params.tools = tools;
188
+ if (body?.top_p != null)
189
+ params.top_p = body.top_p;
190
+ const effort = body?.reasoning_effort ??
191
+ body?.output_config?.effort ??
192
+ (typeof body?.reasoning === "object" ? body.reasoning?.effort : null);
193
+ if (effort && typeof effort === "string") {
194
+ params.reasoning_effort = effort;
195
+ }
196
+ return {
197
+ threadId: toCommandCodeSessionUuid(sessionId),
198
+ memory: null,
199
+ taste: null,
200
+ skills: null,
201
+ permissionMode: "standard",
202
+ config: {
203
+ workingDir: COMMAND_CODE_WORKING_DIR,
204
+ date: new Date().toISOString().slice(0, 10),
205
+ environment: process.platform,
206
+ structure: [],
207
+ isGitRepo: false,
208
+ currentBranch: "",
209
+ mainBranch: "",
210
+ gitStatus: "",
211
+ recentCommits: [],
212
+ },
213
+ params,
214
+ };
215
+ }
@@ -0,0 +1,305 @@
1
+ import { executeUpstreamFetch } from "../../../server/proxy/proxyDispatcher.js";
2
+ import { AnthropicAdapter } from "../../../core/adapters/anthropicAdapter.js";
3
+ import { createResponsesStreamState, openAiChunkToResponsesEvents, finalizeResponsesStream, convertOpenAiResponseToResponsesApi, } from "../../../core/adapters/responsesAdapter.js";
4
+ import { extractSessionId } from "../../../server/proxy/executorHelpers.js";
5
+ import { ResponseLogger } from "../../../server/proxy/responseLogger.js";
6
+ import { SettingsRepository } from "../../../storage/repositories/settingsRepo.js";
7
+ import { logger, LogSymbol, formatDoneLine } from "../../../shared/logger.js";
8
+ import { buildCommandCodeHeaders } from "./headers.js";
9
+ import { CommandCodeUpstreamError, buildCommandCodePayload, commandCodeLineToOpenAiChunks, createCommandCodeStreamState, } from "./converter.js";
10
+ const DEFAULT_COMMAND_CODE_URL = "https://api.commandcode.ai/alpha/generate";
11
+ const RETRYABLE_STATUSES = new Set([502, 503, 504]);
12
+ async function fetchWithRetry(url, headers, payloadStr, proxyUrl, signal) {
13
+ const maxRetries = 2;
14
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
15
+ const res = await executeUpstreamFetch(url, { method: "POST", headers, body: payloadStr, signal }, proxyUrl);
16
+ if (res.ok)
17
+ return { response: res };
18
+ const errText = await res.text().catch(() => "");
19
+ let status = res.status;
20
+ let message = errText || res.statusText;
21
+ try {
22
+ const parsed = JSON.parse(errText);
23
+ const errObj = parsed?.error || parsed;
24
+ message = errObj?.message || parsed?.message || message;
25
+ status = Number(errObj?.code || errObj?.statusCode || status) || status;
26
+ }
27
+ catch { }
28
+ if (RETRYABLE_STATUSES.has(status) && attempt < maxRetries) {
29
+ await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
30
+ continue;
31
+ }
32
+ return { errorResult: { ok: false, status, error: message } };
33
+ }
34
+ return { errorResult: { ok: false, status: 503, error: "CommandCode upstream unavailable" } };
35
+ }
36
+ function recordCommandCodeSuccess(context, targetModel, usage, text, clientResponse) {
37
+ const { req, startTime, requestId, reqTag = "CMC" } = context;
38
+ const durationMs = Date.now() - startTime;
39
+ const promptTokens = usage?.prompt_tokens || context.rtkStats?.compressedTokens || 0;
40
+ const completionTokens = usage?.completion_tokens || Math.ceil(text.length / 4);
41
+ const cachedTokens = usage?.prompt_tokens_details?.cached_tokens || 0;
42
+ const cacheCreationTokens = usage?.cache_creation_input_tokens || 0;
43
+ const calculatedCost = ResponseLogger.logSuccess({
44
+ requestId,
45
+ startTime,
46
+ durationMs,
47
+ clientTool: context.clientTool || "generic",
48
+ rawModel: context.rawModel || targetModel,
49
+ targetModel,
50
+ providerId: "commandcode",
51
+ accountId: context.account?.id,
52
+ accountName: context.account?.name,
53
+ apiKeyId: context.apiKeyId,
54
+ apiKeyName: context.apiKeyName,
55
+ promptTokens,
56
+ completionTokens,
57
+ cachedTokens,
58
+ cacheCreationTokens,
59
+ reasoningTokens: 0,
60
+ tokensSavedByRtk: context.rtkStats?.tokensSaved || 0,
61
+ is1mContext: context.is1mContext,
62
+ requestHeaders: req?.headers || {},
63
+ requestBody: req?.body,
64
+ clientResponse,
65
+ });
66
+ const doneMsg = formatDoneLine({
67
+ durationMs,
68
+ promptTokens,
69
+ completionTokens,
70
+ tokensSaved: context.rtkStats?.tokensSaved || 0,
71
+ cost: calculatedCost,
72
+ });
73
+ logger.line(reqTag, LogSymbol.SUCCESS, `commandcode/${targetModel} · ${doneMsg}`);
74
+ }
75
+ export async function executeCommandCode(context) {
76
+ const { req, res, clientFormat, isPanel, requestId } = context;
77
+ if (!res) {
78
+ return { ok: false, status: 500, error: "Response object is required for CommandCode execution" };
79
+ }
80
+ const targetModel = context.targetModel || "deepseek/deepseek-v4-pro";
81
+ const rawBody = context.body || req?.body || {};
82
+ const openAiBody = clientFormat === "anthropic" ? AnthropicAdapter.anthropicToOpenAi(rawBody) : rawBody;
83
+ const isStreaming = rawBody.stream !== false && !isPanel;
84
+ const globalSettings = SettingsRepository.getEndpointSettings();
85
+ const mergedCustomHeaders = {
86
+ ...(globalSettings.customHeaders || {}),
87
+ ...(context.provider?.customHeaders || {}),
88
+ };
89
+ const sessionId = extractSessionId(req, rawBody);
90
+ const payload = buildCommandCodePayload(targetModel, openAiBody, sessionId);
91
+ const apiKey = (context.account?.rawApiKey || "").trim();
92
+ const headers = buildCommandCodeHeaders({
93
+ apiKey,
94
+ sessionId: payload.threadId,
95
+ accept: "text/event-stream",
96
+ customHeaders: mergedCustomHeaders,
97
+ });
98
+ const targetUrl = (context.account?.providerSpecificData?.baseUrl || "").trim() ||
99
+ (context.provider?.baseUrl || "").trim() ||
100
+ DEFAULT_COMMAND_CODE_URL;
101
+ const effectiveProxy = (context.provider?.proxyUrl || "").trim() || (globalSettings.proxyUrl || "").trim();
102
+ const abortController = new AbortController();
103
+ const onClientClose = () => abortController.abort();
104
+ if (typeof res?.once === "function")
105
+ res.once("close", onClientClose);
106
+ try {
107
+ const { response: upstreamRes, errorResult } = await fetchWithRetry(targetUrl, headers, JSON.stringify(payload), effectiveProxy, abortController.signal);
108
+ if (errorResult || !upstreamRes)
109
+ return errorResult || { ok: false, status: 502, error: "CommandCode failed" };
110
+ const reader = upstreamRes.body?.getReader();
111
+ if (!reader)
112
+ return { ok: false, status: 502, error: "Empty response stream from CommandCode" };
113
+ const decoder = new TextDecoder();
114
+ const state = createCommandCodeStreamState(targetModel, requestId);
115
+ if (isStreaming) {
116
+ let headersSent = false;
117
+ const anthropicState = clientFormat === "anthropic" ? AnthropicAdapter.createStreamState(`msg_${requestId}`, openAiBody.tools) : undefined;
118
+ const responsesState = clientFormat === "responses" ? createResponsesStreamState(requestId) : undefined;
119
+ const ensureSseHeaders = () => {
120
+ if (headersSent || res.writableEnded || res.destroyed)
121
+ return;
122
+ headersSent = true;
123
+ res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
124
+ res.setHeader("Cache-Control", "no-cache");
125
+ res.setHeader("Connection", "keep-alive");
126
+ res.flushHeaders?.();
127
+ if (clientFormat === "anthropic" && anthropicState && !anthropicState.messageStartSent) {
128
+ anthropicState.messageStartSent = true;
129
+ res.write(`event: message_start\ndata: ${JSON.stringify({
130
+ type: "message_start",
131
+ message: { id: `msg_${requestId}`, type: "message", role: "assistant", model: targetModel, content: [] },
132
+ })}\n\n`);
133
+ }
134
+ };
135
+ const writeChunk = (chunk) => {
136
+ if (res.writableEnded || res.destroyed)
137
+ return;
138
+ ensureSseHeaders();
139
+ if (clientFormat === "responses" && responsesState) {
140
+ for (const ev of openAiChunkToResponsesEvents(chunk, responsesState)) {
141
+ res.write(`event: ${ev.event}\ndata: ${JSON.stringify(ev.data)}\n\n`);
142
+ }
143
+ }
144
+ else if (clientFormat === "anthropic" && anthropicState) {
145
+ for (const ev of AnthropicAdapter.openAiChunkToAnthropicEvent(chunk, `msg_${requestId}`, anthropicState)) {
146
+ res.write(ev);
147
+ }
148
+ }
149
+ else {
150
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`);
151
+ }
152
+ };
153
+ let buffer = "";
154
+ let contentText = "";
155
+ let lastUsage = null;
156
+ try {
157
+ while (true) {
158
+ const { done, value } = await reader.read();
159
+ if (done)
160
+ break;
161
+ buffer += decoder.decode(value, { stream: true });
162
+ const lines = buffer.split("\n");
163
+ buffer = lines.pop() || "";
164
+ for (const line of lines) {
165
+ for (const c of commandCodeLineToOpenAiChunks(line, state)) {
166
+ if (c.choices?.[0]?.delta?.content)
167
+ contentText += c.choices[0].delta.content;
168
+ if (c.usage)
169
+ lastUsage = c.usage;
170
+ writeChunk(c);
171
+ }
172
+ }
173
+ }
174
+ if (buffer.trim()) {
175
+ for (const c of commandCodeLineToOpenAiChunks(buffer.trim(), state)) {
176
+ if (c.choices?.[0]?.delta?.content)
177
+ contentText += c.choices[0].delta.content;
178
+ if (c.usage)
179
+ lastUsage = c.usage;
180
+ writeChunk(c);
181
+ }
182
+ }
183
+ }
184
+ catch (err) {
185
+ const status = err instanceof CommandCodeUpstreamError ? err.statusCode : 502;
186
+ if (headersSent && !res.writableEnded && !res.destroyed)
187
+ res.end();
188
+ return { ok: false, status, error: err?.message || "CommandCode stream error" };
189
+ }
190
+ if (!res.writableEnded && !res.destroyed) {
191
+ ensureSseHeaders();
192
+ if (clientFormat === "responses" && responsesState) {
193
+ for (const ev of finalizeResponsesStream(responsesState)) {
194
+ res.write(`event: ${ev.event}\ndata: ${JSON.stringify(ev.data)}\n\n`);
195
+ }
196
+ res.write("data: [DONE]\n\n");
197
+ }
198
+ else if (clientFormat === "anthropic" && anthropicState) {
199
+ for (const ev of AnthropicAdapter.finalizeStream(anthropicState))
200
+ res.write(ev);
201
+ }
202
+ else {
203
+ res.write("data: [DONE]\n\n");
204
+ }
205
+ res.end();
206
+ }
207
+ recordCommandCodeSuccess(context, targetModel, lastUsage, contentText, {
208
+ status: 200,
209
+ headers: { "content-type": "text/event-stream" },
210
+ body: { text: "Stream completed" },
211
+ });
212
+ return { ok: true, status: 200, logged: true, modelUsed: targetModel, text: contentText };
213
+ }
214
+ // Non-streaming / isPanel
215
+ let buffer = "";
216
+ let fullText = "";
217
+ let reasoningText = "";
218
+ const toolCallsByIndex = new Map();
219
+ let finishReason = "stop";
220
+ let usage = undefined;
221
+ const consumeLine = (line) => {
222
+ for (const c of commandCodeLineToOpenAiChunks(line, state)) {
223
+ const d = c.choices?.[0]?.delta;
224
+ if (d?.content)
225
+ fullText += d.content;
226
+ if (d?.reasoning_content)
227
+ reasoningText += d.reasoning_content;
228
+ if (Array.isArray(d?.tool_calls)) {
229
+ for (const tc of d.tool_calls) {
230
+ const existing = toolCallsByIndex.get(tc.index) || {
231
+ id: tc.id || `call_${tc.index}`,
232
+ type: "function",
233
+ function: { name: tc.function?.name || "", arguments: "" },
234
+ };
235
+ if (tc.id)
236
+ existing.id = tc.id;
237
+ if (tc.function?.name)
238
+ existing.function.name = tc.function.name;
239
+ if (tc.function?.arguments)
240
+ existing.function.arguments += tc.function.arguments;
241
+ toolCallsByIndex.set(tc.index, existing);
242
+ }
243
+ }
244
+ if (c.choices?.[0]?.finish_reason)
245
+ finishReason = c.choices[0].finish_reason;
246
+ if (c.usage)
247
+ usage = c.usage;
248
+ }
249
+ };
250
+ try {
251
+ while (true) {
252
+ const { done, value } = await reader.read();
253
+ if (done)
254
+ break;
255
+ buffer += decoder.decode(value, { stream: true });
256
+ const lines = buffer.split("\n");
257
+ buffer = lines.pop() || "";
258
+ for (const line of lines)
259
+ consumeLine(line);
260
+ }
261
+ if (buffer.trim())
262
+ consumeLine(buffer.trim());
263
+ }
264
+ catch (err) {
265
+ const status = err instanceof CommandCodeUpstreamError ? err.statusCode : 502;
266
+ return { ok: false, status, error: err?.message || "CommandCode upstream error" };
267
+ }
268
+ const openAiResp = {
269
+ id: state.responseId,
270
+ object: "chat.completion",
271
+ created: state.created,
272
+ model: targetModel,
273
+ choices: [{
274
+ index: 0,
275
+ message: {
276
+ role: "assistant",
277
+ content: fullText || null,
278
+ ...(reasoningText ? { reasoning_content: reasoningText } : {}),
279
+ ...(toolCallsByIndex.size > 0 ? { tool_calls: Array.from(toolCallsByIndex.values()) } : {}),
280
+ },
281
+ finish_reason: finishReason,
282
+ }],
283
+ ...(usage ? { usage } : {}),
284
+ };
285
+ if (isPanel) {
286
+ return { ok: true, status: 200, json: openAiResp, text: fullText, logged: false, modelUsed: targetModel };
287
+ }
288
+ const outBody = clientFormat === "anthropic"
289
+ ? AnthropicAdapter.openAiResponseToAnthropic(openAiResp)
290
+ : clientFormat === "responses"
291
+ ? convertOpenAiResponseToResponsesApi(openAiResp)
292
+ : openAiResp;
293
+ res.status(200).json(outBody);
294
+ recordCommandCodeSuccess(context, targetModel, usage, fullText, {
295
+ status: 200,
296
+ headers: { "content-type": "application/json" },
297
+ body: outBody,
298
+ });
299
+ return { ok: true, status: 200, json: outBody, text: fullText, logged: true, modelUsed: targetModel };
300
+ }
301
+ finally {
302
+ if (typeof res?.removeListener === "function")
303
+ res.removeListener("close", onClientClose);
304
+ }
305
+ }