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.
Files changed (101) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/commands/logs.js +0 -1
  3. package/dist/core/adapters/anthropic/requestAnthropicToOpenAi.js +59 -11
  4. package/dist/core/adapters/anthropic/requestOpenAiToAnthropic.js +1 -1
  5. package/dist/core/adapters/anthropicAdapter.js +2 -2
  6. package/dist/core/adapters/helpers/toolCallRescue.js +1 -1
  7. package/dist/core/adapters/responsesAdapter.js +11 -0
  8. package/dist/core/capabilities/modelDictionary.js +1 -0
  9. package/dist/core/scanner/modelScanner.js +2 -1
  10. package/dist/core/scanner/payloadExtractor.js +1 -1
  11. package/dist/core/scanner/urlResolver.js +16 -0
  12. package/dist/core/tokenSaver/methods/rtk/autodetect.js +1 -1
  13. package/dist/core/tokenSaver/methods/rtk/filters/gitLog.js +1 -1
  14. package/dist/core/usage/pricing.js +98 -42
  15. package/dist/core/usage/tokenExtractor.js +59 -0
  16. package/dist/mitm/handlers/antigravity/config.js +22 -0
  17. package/dist/mitm/handlers/antigravity/modelInjector.js +2 -2
  18. package/dist/providers/catalog/commandcode/converter.js +215 -0
  19. package/dist/providers/catalog/commandcode/executor.js +305 -0
  20. package/dist/providers/catalog/commandcode/headers.js +76 -0
  21. package/dist/providers/catalog/commandcode/metadata.js +4 -1
  22. package/dist/providers/catalog/commandcode/ndjson.js +161 -0
  23. package/dist/providers/catalog/commandcode/provider.js +18 -35
  24. package/dist/providers/catalog/commandcode/routes.js +75 -0
  25. package/dist/providers/catalog/iflow/provider.js +1 -1
  26. package/dist/providers/catalog/iteracompute/metadata.js +154 -13
  27. package/dist/providers/catalog/iteracompute/provider.js +111 -0
  28. package/dist/providers/catalog/opencode-go/metadata.js +4 -2
  29. package/dist/providers/catalog/opencode-go/models.js +1 -0
  30. package/dist/providers/catalog/opencode-go/provider.js +114 -0
  31. package/dist/providers/catalog/opencode-go/quota.js +106 -0
  32. package/dist/providers/catalog/opencode-go/responses.js +301 -0
  33. package/dist/providers/catalog/opencode-go/responsesPayload.js +228 -0
  34. package/dist/providers/catalog/openrouter/metadata.js +1 -0
  35. package/dist/providers/catalog/sensenova/metadata.js +35 -0
  36. package/dist/providers/core/base/baseProvider.js +8 -3
  37. package/dist/providers/core/base/openAiProvider.js +3 -1
  38. package/dist/providers/generated/routesRegistry.generated.js +2 -0
  39. package/dist/providers/runtime/antigravity/executor.js +2 -2
  40. package/dist/providers/runtime/antigravity/metadata.js +2 -2
  41. package/dist/providers/runtime/antigravity/models.js +9 -0
  42. package/dist/providers/runtime/antigravity/provider.js +2 -2
  43. package/dist/providers/runtime/antigravity/routes.js +2 -2
  44. package/dist/providers/runtime/antigravity/schema.js +20 -2
  45. package/dist/providers/runtime/antigravity/types.js +10 -2
  46. package/dist/providers/runtime/codebuddy/provider.js +21 -6
  47. package/dist/providers/runtime/gemini/provider.js +77 -0
  48. package/dist/providers/runtime/gemini-cli/provider.js +2 -2
  49. package/dist/providers/runtime/github/routes.js +1 -1
  50. package/dist/providers/runtime/grok/provider.js +1 -1
  51. package/dist/providers/runtime/kiro/executor.js +7 -4
  52. package/dist/providers/runtime/kiro/models.js +11 -0
  53. package/dist/providers/runtime/kiro/provider.js +8 -8
  54. package/dist/providers/runtime/minimax/routes.js +0 -1
  55. package/dist/providers/runtime/opencode/tools.js +39 -17
  56. package/dist/providers/runtime/windsurf/routes.js +0 -2
  57. package/dist/providers/runtime/xkiro/quota.js +4 -1
  58. package/dist/server/proxy/executorHelpers.js +1 -1
  59. package/dist/server/proxy/index.js +1 -1
  60. package/dist/server/proxy/pipeline.js +12 -6
  61. package/dist/server/proxy/proxyDispatcher.js +136 -17
  62. package/dist/server/proxy/responseHandlers.js +2 -18
  63. package/dist/server/proxy/singleModelExecutor.js +15 -3
  64. package/dist/server/proxy/streaming/sseStreamer.js +3 -10
  65. package/dist/server/routes/apiMitm.js +1 -1
  66. package/dist/server/routes/apiModels.js +17 -12
  67. package/dist/server/utils/consoleLogBuffer.js +3 -3
  68. package/dist/shared/constants/index.js +2 -2
  69. package/dist/shared/logger.js +2 -2
  70. package/dist/shared/utils/dnsResolver.js +69 -27
  71. package/dist/storage/repositories/logRepo.js +3 -23
  72. package/dist/storage/repositories/requestDetailsRepo.js +1 -1
  73. package/dist/storage/repositories/usageRepo.js +136 -74
  74. package/dist/web/assets/{CliToolsTab-D4DkK7Rn.js → CliToolsTab-rKSWLJC3.js} +1 -1
  75. package/dist/web/assets/CombosTab-D1_cfssh.js +1 -0
  76. package/dist/web/assets/{ConfirmModal-CuQ7ARxt.js → ConfirmModal-OWeauwYv.js} +1 -1
  77. package/dist/web/assets/{ConsoleLogTab-B2sfhYZW.js → ConsoleLogTab-rZe8zCb_.js} +1 -1
  78. package/dist/web/assets/{EditAccountModal-BusNJLvX.js → EditAccountModal-CAg-yIOn.js} +1 -1
  79. package/dist/web/assets/{EndpointTab-DQCezUA9.js → EndpointTab-B-Jb4wAG.js} +1 -1
  80. package/dist/web/assets/{MitmTab-DxEuD0DW.js → MitmTab-5dKeNi4T.js} +5 -5
  81. package/dist/web/assets/{ModelAutocompleteInput-CgJ2FlEf.js → ModelAutocompleteInput-CoinzdsW.js} +1 -1
  82. package/dist/web/assets/ProviderDetailPage-D-fodBhz.js +6 -0
  83. package/dist/web/assets/ProvidersTab-yzmb4w0D.js +1 -0
  84. package/dist/web/assets/{QuotaTab-CvXGyICr.js → QuotaTab-BXevQzen.js} +1 -1
  85. package/dist/web/assets/{SettingsTab-D7YF7rTP.js → SettingsTab-LkByv4Sg.js} +1 -1
  86. package/dist/web/assets/UsageTab-Hr8XPZD4.js +1 -0
  87. package/dist/web/assets/index-CKuvklEr.js +2 -0
  88. package/dist/web/assets/{index-BisuNW2y.css → index-HnsyZg0I.css} +1 -1
  89. package/dist/web/assets/metadataRegistry-NuDSSkP9.js +1 -0
  90. package/dist/web/assets/providers/openrouter/icon.png +0 -0
  91. package/dist/web/assets/providersData-DS1-ETBi.js +1 -0
  92. package/dist/web/index.html +2 -2
  93. package/package.json +9 -1
  94. package/dist/web/assets/CombosTab-X1C_OmzI.js +0 -1
  95. package/dist/web/assets/ProviderDetailPage-DMA1DVSN.js +0 -6
  96. package/dist/web/assets/ProvidersTab-pZoM69s4.js +0 -1
  97. package/dist/web/assets/UsageTab-B0YCftIJ.js +0 -1
  98. package/dist/web/assets/index-DTRst7wN.js +0 -2
  99. package/dist/web/assets/metadataRegistry-BPZSXiBy.js +0 -1
  100. package/dist/web/assets/providers/openrouter/openrouter.png +0 -0
  101. package/dist/web/assets/providersData-Bsv7o5VV.js +0 -1
@@ -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
+ }
@@ -0,0 +1,76 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { metadata } from "./metadata.js";
3
+ const CHAR_REPLACEMENTS = new Map([
4
+ ["&", " and "],
5
+ ["🦄", " unicorn "],
6
+ ["♥", " love "],
7
+ ["ß", "ss"],
8
+ ["ẞ", "Ss"],
9
+ ["ä", "ae"],
10
+ ["Ä", "Ae"],
11
+ ["ö", "oe"],
12
+ ["Ö", "Oe"],
13
+ ["ü", "ue"],
14
+ ["Ü", "Ue"],
15
+ ["Æ", "AE"],
16
+ ["æ", "ae"],
17
+ ["Ø", "O"],
18
+ ["ø", "o"],
19
+ ["Œ", "OE"],
20
+ ["œ", "oe"],
21
+ ["Ð", "D"],
22
+ ["ð", "d"],
23
+ ["Đ", "D"],
24
+ ["đ", "d"],
25
+ ["Þ", "TH"],
26
+ ["þ", "th"],
27
+ ["Ł", "L"],
28
+ ["ł", "l"],
29
+ ["ı", "i"],
30
+ ]);
31
+ function transliterate(value) {
32
+ let out = "";
33
+ for (const ch of value)
34
+ out += CHAR_REPLACEMENTS.get(ch) ?? ch;
35
+ return out.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
36
+ }
37
+ function decamelize(value) {
38
+ return value
39
+ .replace(/([A-Z]{2,})(\d+)/g, "$1 $2")
40
+ .replace(/([a-z\d]+)([A-Z]{2,})/g, "$1 $2")
41
+ .replace(/([a-z\d])([A-Z])/g, "$1 $2")
42
+ .replace(/([A-Z]+)([A-Z][a-rt-z\d]+)/g, "$1 $2");
43
+ }
44
+ export function slugifyPath(value) {
45
+ return decamelize(transliterate(String(value ?? "")))
46
+ .toLowerCase()
47
+ .replace(/[^a-z\d]+/g, "-")
48
+ .replace(/^-+|-+$/g, "");
49
+ }
50
+ export function toCommandCodeSessionUuid(sessionId) {
51
+ if (!sessionId)
52
+ return randomUUID();
53
+ const h = createHash("sha256").update(String(sessionId)).digest("hex");
54
+ const variant = ((parseInt(h[16], 16) & 0x3) | 0x8).toString(16);
55
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
56
+ }
57
+ export const COMMAND_CODE_WORKING_DIR = process.cwd();
58
+ export const COMMAND_CODE_PROJECT_SLUG = slugifyPath(COMMAND_CODE_WORKING_DIR);
59
+ export function buildCommandCodeHeaders(opts = {}) {
60
+ const headers = {
61
+ "Content-Type": "application/json",
62
+ ...(metadata.defaultHeaders || {}),
63
+ ...(opts.customHeaders || {}),
64
+ "x-project-slug": COMMAND_CODE_PROJECT_SLUG,
65
+ "x-session-id": opts.sessionId || randomUUID(),
66
+ };
67
+ if (opts.apiKey) {
68
+ headers["Authorization"] = opts.apiKey.startsWith("Bearer ")
69
+ ? opts.apiKey
70
+ : `Bearer ${opts.apiKey}`;
71
+ }
72
+ if (opts.accept) {
73
+ headers["Accept"] = opts.accept;
74
+ }
75
+ return headers;
76
+ }
@@ -24,12 +24,15 @@ export const metadata = {
24
24
  "format": "commandcode",
25
25
  "defaultHeaders": {
26
26
  "User-Agent": "cli",
27
- "x-command-code-version": "1.88.0",
27
+ "x-command-code-version": "1.88.5",
28
28
  "x-cli-environment": "production",
29
29
  "x-cli-surface": "cli",
30
30
  "x-taste-learning": "false"
31
31
  },
32
32
  "thinkingMode": "auto",
33
+ "passthroughModels": true,
34
+ "supportsAutoImport": true,
35
+ "autoImportHint": "Import API key directly from ~/.commandcode/auth.json",
33
36
  models
34
37
  };
35
38
  export const provider = metadata;