Files
OmniRoute/open-sse/executors/qoder.ts
Diego Rodrigues de Sa e Souza b100325fe0 chore(release): v3.5.2 — Qoder DashScope Native Integration & Stability (#999)
* feat(qoder): native cosy integration

* feat(qoder): implement native COSY encryption algorithm and remove CLI child instances, plus workflow bumps

* feat(resilience): context overflow fallback, OAuth token detection, empty content guard & context-optimized combo strategy

- Add isContextOverflowError + isContextOverflow detectors (400 + token-limit signals)
- Auto-fallback to next family model on context overflow in chatCore
- Add isEmptyContentResponse to catch fake-success empty responses, trigger fallback + recursive retry
- Add OAUTH_INVALID_TOKEN error type (T11) with isOAuthInvalidToken signal matching; warn instead of deactivating node
- Add getModelContextLimit helper in modelsDevSync (reads limit_context from synced capabilities)
- Upgrade getTokenLimit in contextManager to check models.dev DB before registry (fixes gemini-2.5-pro: 1000000→1048576)
- Add findLargerContextModel in modelFamilyFallback for context-aware model selection
- Add sortModelsByContextSize + context-optimized combo strategy in combo.ts
- Update context-manager unit test for corrected gemini-2.5-pro limit

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(review): address Gemini code review — tool_calls path, infinite recursion, dedup signals, findLargerContextModel

- Fix isEmptyContentResponse: check message.tool_calls/delta.tool_calls instead
  of firstChoice.tool_calls (wrong OpenAI API path, caused tool-call responses
  to be falsely flagged as empty)
- Fix empty content fallback: replace recursive handleChatCore call (infinite
  recursion risk + wrong model due to original body.model) with non-recursive
  pattern — call executeProviderRequest, parse fallback response body, reassign
  responseBody and fall through to existing processing
- Fix context overflow: use findLargerContextModel over family candidates first,
  fall back to getNextFamilyFallback — ensures we pick a model with actually
  larger context window on overflow
- Fix signal dedup: export CONTEXT_OVERFLOW_SIGNALS + CONTEXT_OVERFLOW_REGEX
  from errorClassifier.ts; import shared regex in modelFamilyFallback.ts,
  removing duplicate signal list and per-call RegExp construction

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(UI): add context-optimized strategy to frontend schema and options

* fix(sse): preserve Responses API events in stream translation

When translating Claude-format responses (e.g. GLM) to Responses API
format for Codex CLI, the sanitizer stripped {event, data} structured
items to {"object":"chat.completion.chunk"}, losing all content and
the critical response.completed event.

Only run sanitizeStreamingChunk on OpenAI Chat Completions chunks,
skipping items that have the Responses API {event, data} structure.

* test(sse): add regression test for Claude→Responses stream sanitization

Verifies that {event,data} structured items from the Responses API
translator bypass sanitizeStreamingChunk when translating Claude-format
providers (e.g. GLM) to Responses API format for Codex CLI.

* fix(sse): strengthen Responses API event detection with response. prefix check

Use explicit `response.` prefix check instead of generic `event && data`
presence check, as recommended in PR review.

* fix: pin Next.js to 16.0.10 to prevent Turbopack hashed module bug

Remove ^ prefix from next and eslint-config-next to prevent
automatic upgrades to 16.1.x+ which introduced content-based
hashing for external module references in Turbopack.

Also remove duplicate Material Symbols @import from globals.css
(font already loaded via <link> in layout.tsx).

Fixes #509

* align cc-compatible cache handling with client passthrough

* chore: integrate resilience and turbopack fixes (PRs #992, #990, #987)

* chore(release): bump to v3.5.2 — changelog, docs, version sync

* docs(i18n): sync documentation updates to 33 languages

* fix(qoder): replace any with unknown to comply with strict any-budget

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Chris Staley <christopher-s@users.noreply.github.com>
Co-authored-by: Ivan <shanin-i2011@yandex.ru>
Co-authored-by: R.D. <rogerproself@gmail.com>
2026-04-05 02:54:44 -03:00

159 lines
5.1 KiB
TypeScript

import {
BaseExecutor,
mergeUpstreamExtraHeaders,
type ExecuteInput,
type ProviderCredentials,
} from "./base.ts";
import { PROVIDERS } from "../config/constants.ts";
function getAuthToken(credentials: ProviderCredentials): string {
if (typeof credentials.apiKey === "string" && credentials.apiKey.trim()) {
return credentials.apiKey.trim();
}
if (typeof credentials.accessToken === "string" && credentials.accessToken.trim()) {
return credentials.accessToken.trim();
}
if (typeof credentials.refreshToken === "string" && credentials.refreshToken.trim()) {
return credentials.refreshToken.trim();
}
return "";
}
export class QoderExecutor extends BaseExecutor {
constructor() {
super("qoder", PROVIDERS.qoder);
}
async execute({ model, body, stream, credentials, signal, upstreamExtraHeaders }: ExecuteInput) {
const token = getAuthToken(credentials);
if (!token) {
return {
response: new Response(
JSON.stringify({
error: {
message: "Qoder access token or API Key is required. Please sign in or set a PAT.",
type: "authentication_error",
code: "token_required",
},
}),
{ status: 401, headers: { "Content-Type": "application/json" } }
),
url: "https://dashscope.aliyuncs.com",
headers: { "Content-Type": "application/json" },
transformedBody: body,
};
}
const resolvedModel = model || "qwen3-coder-plus";
// Check if it's a model-alias matching QwenCode
let mappedModel = resolvedModel;
if (resolvedModel === "qwen3.5-plus" || resolvedModel === "qwen3.6-plus") {
mappedModel = "coder-model"; // Translate alias to what DashScope compatible endpoint accepts via QwenCode tokens
} else if (resolvedModel === "vision-model") {
mappedModel = "qwen3-vl-plus";
}
// Determine the resource URL: Qwen CLI tokens usually target portal.qwen.ai natively,
// but the DashScope compatible endpoint works out of the box when authtype is set.
// If the token was mapped to a custom `resource_url`, we should use it. Otherwise default to dashscope Aliyun.
let endpointUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
// We allow setting custom API base via credentials
let credentialsApiBase: unknown;
if (typeof credentials === "object" && credentials !== null) {
const credsObj = credentials as Record<string, unknown>;
credentialsApiBase = credsObj.customApiBase || credsObj.resourceUrl;
}
if (typeof credentialsApiBase === "string" && credentialsApiBase.trim()) {
let base = credentialsApiBase.trim();
if (!base.startsWith("http")) base = `https://${base}`;
if (!base.endsWith("/v1")) base = base.endsWith("/") ? `${base}v1` : `${base}/v1`;
endpointUrl = `${base}/chat/completions`;
}
const headers: Record<string, string> = {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"x-dashscope-authtype": "qwen-oauth",
"x-dashscope-cachecontrol": "enable",
"user-agent": "QwenCode/0.11.1 (linux; x64)",
"x-dashscope-useragent": "QwenCode/0.11.1 (linux; x64)",
"x-stainless-arch": "x64",
"x-stainless-lang": "js",
"x-stainless-os": "Linux",
};
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
const payload = {
...(typeof body === "object" && body !== null ? body : {}),
model: mappedModel,
};
const bodyStr = JSON.stringify(payload);
try {
const response = await fetch(endpointUrl, {
method: "POST",
headers,
body: bodyStr,
signal,
});
const newHeaders = new Headers(response.headers);
if (!response.ok) {
let errText = await response.text();
return {
response: new Response(
JSON.stringify({
error: {
message: `Qoder API failed with status ${response.status}: ${errText}`,
type: response.status === 401 ? "authentication_error" : "provider_error",
},
}),
{ status: response.status, headers: { "Content-Type": "application/json" } }
),
url: endpointUrl,
headers,
transformedBody: payload,
};
}
return {
response: new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
}),
url: endpointUrl,
headers,
transformedBody: payload,
};
} catch (e: unknown) {
const error = e as Error;
if (error.name === "AbortError") {
throw error;
}
return {
response: new Response(
JSON.stringify({
error: {
message: `Qoder fetch error: ${error.message}`,
type: "provider_error",
},
}),
{ status: 502, headers: { "Content-Type": "application/json" } }
),
url: endpointUrl,
headers,
transformedBody: payload,
};
}
}
}
export default QoderExecutor;