mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-19 22:45:45 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e4195bf7f | ||
|
|
9c292460e3 |
No files matched your search
@@ -85,7 +85,6 @@ export const enAiMessages: Messages = {
|
||||
'ai.providers.test.ok': 'Connected ({latency} ms)',
|
||||
'ai.providers.test.warn': 'Reached endpoint, but response looks incomplete ({latency} ms)',
|
||||
'ai.providers.test.warnSlow': 'Connected, but slow ({latency} ms)',
|
||||
'ai.providers.test.modelListUnavailable': 'Model list unavailable (HTTP 404). Enter a model ID manually, then try a chat to verify the connection.',
|
||||
'ai.providers.test.error': 'Failed ({detail})',
|
||||
'ai.providers.test.missingBaseUrl': 'Enter a Base URL first',
|
||||
'ai.providers.test.missingApiKey': 'Enter an API key first',
|
||||
|
||||
@@ -76,7 +76,6 @@ export const esAiMessages: Messages = {
|
||||
'ai.providers.test.ok': 'Conectado ({latency} ms)',
|
||||
'ai.providers.test.warn': 'Se alcanzó el endpoint, pero la respuesta parece incompleta ({latency} ms)',
|
||||
'ai.providers.test.warnSlow': 'Conectado, pero lento ({latency} ms)',
|
||||
'ai.providers.test.modelListUnavailable': 'Lista de modelos no disponible (HTTP 404). Introduce el ID de un modelo y prueba un chat para verificar la conexión.',
|
||||
'ai.providers.test.error': 'Falló ({detail})',
|
||||
'ai.providers.test.missingBaseUrl': 'Primero ingresa una URL base',
|
||||
'ai.providers.test.missingApiKey': 'Primero ingresa una clave de API',
|
||||
|
||||
@@ -57,7 +57,6 @@ export const ruAiMessages: Messages = {
|
||||
'ai.providers.test.ok': 'Подключено ({latency} ms)',
|
||||
'ai.providers.test.warn': 'Эндпоинт доступен, но ответ выглядит неполным ({latency} ms)',
|
||||
'ai.providers.test.warnSlow': 'Подключено, но медленно ({latency} ms)',
|
||||
'ai.providers.test.modelListUnavailable': 'Список моделей недоступен (HTTP 404). Введите ID модели вручную и отправьте сообщение в чате, чтобы проверить подключение.',
|
||||
'ai.providers.test.error': 'Ошибка ({detail})',
|
||||
'ai.providers.test.missingBaseUrl': 'Сначала укажите Base URL',
|
||||
'ai.providers.test.missingApiKey': 'Сначала укажите API-ключ',
|
||||
|
||||
@@ -85,7 +85,6 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.providers.test.ok': '连接正常({latency} ms)',
|
||||
'ai.providers.test.warn': '已连通,但响应不完整({latency} ms)',
|
||||
'ai.providers.test.warnSlow': '已连通,但较慢({latency} ms)',
|
||||
'ai.providers.test.modelListUnavailable': '无法获取模型列表(HTTP 404)。请手动填写模型 ID,再发送一条消息验证连接。',
|
||||
'ai.providers.test.error': '检测失败({detail})',
|
||||
'ai.providers.test.missingBaseUrl': '请先填写 Base URL',
|
||||
'ai.providers.test.missingApiKey': '请先填写 API Key',
|
||||
|
||||
@@ -85,7 +85,6 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.providers.test.ok': '連線正常({latency} ms)',
|
||||
'ai.providers.test.warn': '已連通,但回應不完整({latency} ms)',
|
||||
'ai.providers.test.warnSlow': '已連通,但較慢({latency} ms)',
|
||||
'ai.providers.test.modelListUnavailable': '無法取得模型清單(HTTP 404)。請手動輸入模型 ID,再傳送一則訊息驗證連線。',
|
||||
'ai.providers.test.error': '檢測失敗({detail})',
|
||||
'ai.providers.test.missingBaseUrl': '請先填寫 Base URL',
|
||||
'ai.providers.test.missingApiKey': '請先填寫 API Key',
|
||||
|
||||
@@ -154,7 +154,7 @@ export const ModelSelector: React.FC<{
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, effectiveModelsEndpoint);
|
||||
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders);
|
||||
const headers = buildModelDiscoveryHeaders(resolvedStyle, apiKey, customHeaders, baseURL);
|
||||
const result = await bridge.aiFetch(url, "GET", headers, undefined, undefined, undefined, undefined, skipTLSVerify);
|
||||
if (!result.ok) {
|
||||
if (discoveryKeyRef.current !== requestKey) return;
|
||||
|
||||
@@ -339,11 +339,9 @@ export const ProviderConfigForm: React.FC<{
|
||||
message: t("ai.providers.test.ok", { latency }),
|
||||
});
|
||||
} else if (classified.health === "warn") {
|
||||
const warnKey = classified.notice === "model-list-unavailable"
|
||||
? "ai.providers.test.modelListUnavailable"
|
||||
: classified.modelCount === 0 || classified.error
|
||||
? "ai.providers.test.warn"
|
||||
: "ai.providers.test.warnSlow";
|
||||
const warnKey = classified.modelCount === 0 || classified.error
|
||||
? "ai.providers.test.warn"
|
||||
: "ai.providers.test.warnSlow";
|
||||
setProbeResult({
|
||||
health: "warn",
|
||||
message: t(warnKey, { latency }),
|
||||
|
||||
@@ -374,3 +374,14 @@ test('side panel close button stays visible at every panel width', () => {
|
||||
assert.match(closeSlice, /className="h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent"/);
|
||||
assert.doesNotMatch(closeSlice, /\bhidden\b|max-(sm|md|lg|xl):/);
|
||||
});
|
||||
|
||||
test('magnified side-panel chrome thickens the accent stroke on low-DPR displays', () => {
|
||||
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
|
||||
const overlay = source.slice(
|
||||
source.indexOf('data-section="pane-magnification-overlay"'),
|
||||
source.indexOf('data-section="pane-magnification-content"'),
|
||||
);
|
||||
assert.match(overlay, /overflow-hidden rounded-md border bg-background shadow-2xl/);
|
||||
assert.match(overlay, /borderColor: sidePanelTheme\.accent,/);
|
||||
assert.match(overlay, /resolveMagnifiedChromeBorderWidth\(/);
|
||||
});
|
||||
@@ -64,7 +64,7 @@ import { PersistentSidePanelPortal, SidePanelMountedContent } from './terminalLa
|
||||
import { usePluginTerminalSidebar } from '../../application/state/usePluginTerminalSidebar';
|
||||
import { PluginTerminalSidebarPageHost } from '../plugins/PluginTerminalSidebar';
|
||||
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
|
||||
import { getPaneMagnificationShortcutLabel } from '../../domain/paneMagnification';
|
||||
import { getPaneMagnificationShortcutLabel, resolveMagnifiedChromeBorderWidth } from '../../domain/paneMagnification';
|
||||
|
||||
const MemoizedSidePanelMountedContent = memo(
|
||||
SidePanelMountedContent,
|
||||
@@ -1545,6 +1545,9 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
|
||||
className="absolute inset-3 flex flex-col overflow-hidden rounded-md border bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
|
||||
style={{
|
||||
borderColor: sidePanelTheme.accent,
|
||||
borderWidth: resolveMagnifiedChromeBorderWidth(
|
||||
typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1),
|
||||
),
|
||||
backgroundColor: sidePanelTheme.termBg,
|
||||
color: sidePanelTheme.termFg,
|
||||
}}
|
||||
|
||||
@@ -52,6 +52,7 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
|
||||
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
|
||||
import type { SidePanelTool } from '../../domain/sidePanelLayout';
|
||||
import {
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolvePaneMagnificationStyle,
|
||||
type PaneMagnificationController,
|
||||
type PaneMagnificationTarget,
|
||||
@@ -1439,10 +1440,12 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
observer.observe(surface);
|
||||
return () => observer.disconnect();
|
||||
}, [isMagnified]);
|
||||
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
|
||||
const style: React.CSSProperties = resolvePaneMagnificationStyle(
|
||||
layoutStyle,
|
||||
isMagnified && !!magnifiedSurfaceBounds,
|
||||
magnifiedSurfaceBounds,
|
||||
magnifiedDevicePixelRatio,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
@@ -1605,6 +1608,9 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
|
||||
style={{
|
||||
...style,
|
||||
borderColor: isMagnified && magnifiedSurfaceBounds ? sessionAppearanceTheme.colors.cursor : undefined,
|
||||
borderWidth: isMagnified && magnifiedSurfaceBounds
|
||||
? resolveMagnifiedChromeBorderWidth(magnifiedDevicePixelRatio)
|
||||
: undefined,
|
||||
}}
|
||||
tabIndex={-1}
|
||||
onClick={handlePaneClick}
|
||||
|
||||
@@ -15,6 +15,14 @@ test("magnified terminal panes use the resolved terminal accent for border chrom
|
||||
|
||||
assert.match(paneSource, /isMagnified && magnifiedSurfaceBounds && "overflow-hidden rounded-md border shadow-2xl /);
|
||||
assert.match(paneSource, /borderColor: isMagnified && magnifiedSurfaceBounds \? sessionAppearanceTheme\.colors\.cursor : undefined/);
|
||||
assert.match(paneSource, /borderWidth: isMagnified && magnifiedSurfaceBounds/);
|
||||
assert.match(paneSource, /resolveMagnifiedChromeBorderWidth\(magnifiedDevicePixelRatio\)/);
|
||||
});
|
||||
|
||||
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
|
||||
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
|
||||
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*\)/);
|
||||
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
|
||||
});
|
||||
|
||||
test("terminal keyboard focus updates the pane selected for magnification", () => {
|
||||
|
||||
@@ -7,7 +7,9 @@ import {
|
||||
isPaneMagnificationSelectionValid,
|
||||
resolvePaneMagnificationCandidate,
|
||||
resolvePaneMagnificationStyle,
|
||||
resolveMagnifiedChromeBorderWidth,
|
||||
resolveTwoPaneMagnificationStyle,
|
||||
snapCssRectToDevicePixels,
|
||||
type PaneMagnificationController,
|
||||
} from './paneMagnification.ts';
|
||||
|
||||
@@ -90,6 +92,53 @@ test('magnification overlays the original layout without changing its rect', ()
|
||||
});
|
||||
});
|
||||
|
||||
test('magnified chrome uses a 2px accent stroke only below 1.5 device pixels', () => {
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.2), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.49), 2);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(1.5), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(2), 1);
|
||||
assert.equal(resolveMagnifiedChromeBorderWidth(0), 1);
|
||||
});
|
||||
|
||||
test('magnified surface bounds snap to the device-pixel grid after the 12px inset', () => {
|
||||
const original = { left: '0px', top: '0px', width: '100px', height: '100px' };
|
||||
// Integer CSS pixels at 1x stay unchanged (existing contract).
|
||||
assert.deepEqual(resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120,
|
||||
top: 80,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 1), {
|
||||
position: 'fixed',
|
||||
left: '132px',
|
||||
top: '92px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
// 120.4+12=132.4 at 2x -> 264.8 rounds to 265 -> 132.5
|
||||
// right: 120.4+1400-12=1508.4 at 2x -> 3016.8 rounds to 3017 -> 1508.5
|
||||
const snapped = resolvePaneMagnificationStyle(original, true, {
|
||||
left: 120.4,
|
||||
top: 80.4,
|
||||
width: 1400,
|
||||
height: 900,
|
||||
}, 2);
|
||||
assert.deepEqual(snapped, {
|
||||
position: 'fixed',
|
||||
left: '132.5px',
|
||||
top: '92.5px',
|
||||
width: '1376px',
|
||||
height: '876px',
|
||||
zIndex: 50,
|
||||
});
|
||||
|
||||
const rect = snapCssRectToDevicePixels(10.2, 20.2, 110.2, 80.2, 2);
|
||||
assert.deepEqual(rect, { left: 10, top: 20, width: 100, height: 60 });
|
||||
});
|
||||
|
||||
test('two-pane magnification keeps the dormant pane geometry unchanged', () => {
|
||||
assert.deepEqual(resolveTwoPaneMagnificationStyle('left', true, true), {
|
||||
left: '12px', top: '12px', width: 'calc(100% - 24px)', height: 'calc(100% - 24px)', zIndex: 50,
|
||||
|
||||
@@ -92,19 +92,52 @@ export function getPaneMagnificationShortcutLabel(
|
||||
return (hotkeyScheme === 'mac' ? binding?.mac : binding?.pc)?.replace(/ \+ /g, '+') ?? '';
|
||||
}
|
||||
|
||||
export function resolveMagnifiedChromeBorderWidth(devicePixelRatio = 1): number {
|
||||
return devicePixelRatio > 0 && devicePixelRatio < 1.5 ? 2 : 1;
|
||||
}
|
||||
|
||||
export function snapCssRectToDevicePixels(
|
||||
left: number,
|
||||
top: number,
|
||||
right: number,
|
||||
bottom: number,
|
||||
devicePixelRatio = 1,
|
||||
): { left: number; top: number; width: number; height: number } {
|
||||
const dpr = devicePixelRatio > 0 ? devicePixelRatio : 1;
|
||||
const snap = (value: number) => Math.round(value * dpr) / dpr;
|
||||
const snappedLeft = snap(left);
|
||||
const snappedTop = snap(top);
|
||||
const snappedRight = snap(right);
|
||||
const snappedBottom = snap(bottom);
|
||||
return {
|
||||
left: snappedLeft,
|
||||
top: snappedTop,
|
||||
width: Math.max(0, snappedRight - snappedLeft),
|
||||
height: Math.max(0, snappedBottom - snappedTop),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePaneMagnificationStyle(
|
||||
original: React.CSSProperties,
|
||||
magnified: boolean,
|
||||
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
|
||||
devicePixelRatio = 1,
|
||||
): React.CSSProperties {
|
||||
if (!magnified) return original;
|
||||
if (surfaceBounds) {
|
||||
const snapped = snapCssRectToDevicePixels(
|
||||
surfaceBounds.left + 12,
|
||||
surfaceBounds.top + 12,
|
||||
surfaceBounds.left + surfaceBounds.width - 12,
|
||||
surfaceBounds.top + surfaceBounds.height - 12,
|
||||
devicePixelRatio,
|
||||
);
|
||||
return {
|
||||
position: 'fixed',
|
||||
left: `${surfaceBounds.left + 12}px`,
|
||||
top: `${surfaceBounds.top + 12}px`,
|
||||
width: `${Math.max(0, surfaceBounds.width - 24)}px`,
|
||||
height: `${Math.max(0, surfaceBounds.height - 24)}px`,
|
||||
left: `${snapped.left}px`,
|
||||
top: `${snapped.top}px`,
|
||||
width: `${snapped.width}px`,
|
||||
height: `${snapped.height}px`,
|
||||
zIndex: 50,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,3 +71,19 @@ test("normalizeAnthropicSdkBaseURL preserves custom non-/v1 path prefixes", () =
|
||||
"https://gateway.example/api/v1",
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizes the official Ark Agent Plan Anthropic prefix only", () => {
|
||||
const base = "https://ark.cn-beijing.volces.com/api/plan";
|
||||
for (const input of [base, base + "/", " " + base + " ", base + "/v1", base + "/v1/"]) {
|
||||
assert.equal(normalizeAnthropicSdkBaseURL(input), base + "/v1");
|
||||
}
|
||||
for (const input of [
|
||||
base.replace("https:", "http:"),
|
||||
base.replace(".com", ".com.example"),
|
||||
base.replace(".com", ".com:8443"),
|
||||
base + "/custom",
|
||||
"https://gateway.example/api/plan",
|
||||
]) {
|
||||
assert.equal(normalizeAnthropicSdkBaseURL(input), input);
|
||||
}
|
||||
});
|
||||
@@ -39,6 +39,7 @@ export function isBareOriginBaseURL(baseURL: string): boolean {
|
||||
* Normalize a stored Anthropic-compat Base URL for @ai-sdk/anthropic.
|
||||
* - Bare hosts gain a /v1 suffix (Claude Code style → SDK style).
|
||||
* - Bases that already end in /v1 are left unchanged.
|
||||
* - The official Ark Agent Plan /api/plan prefix gains a /v1 suffix.
|
||||
* - Other path prefixes (custom proxies) are left unchanged so chat keeps
|
||||
* requesting `{prefix}/messages` rather than `{prefix}/v1/messages`.
|
||||
*/
|
||||
@@ -46,6 +47,9 @@ export function normalizeAnthropicSdkBaseURL(baseURL: string): string {
|
||||
const trimmed = stripTrailingSlashes(baseURL);
|
||||
if (!trimmed) return trimmed;
|
||||
if (anthropicBaseIncludesV1(trimmed)) return trimmed;
|
||||
// Claude Code appends /v1/messages to the documented Ark Agent Plan base.
|
||||
// The Anthropic SDK appends only /messages, so supply the missing /v1.
|
||||
if (trimmed === "https://ark.cn-beijing.volces.com/api/plan") return `${trimmed}/v1`;
|
||||
if (!isBareOriginBaseURL(trimmed)) return trimmed;
|
||||
return `${trimmed}/v1`;
|
||||
}
|
||||
@@ -142,7 +142,12 @@ export async function fetchProviderModelCatalog(
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, endpoint);
|
||||
const headers = buildModelDiscoveryHeaders(style, apiKey, await decryptProviderHeaders(provider.customHeaders));
|
||||
const headers = buildModelDiscoveryHeaders(
|
||||
style,
|
||||
apiKey,
|
||||
await decryptProviderHeaders(provider.customHeaders),
|
||||
baseURL,
|
||||
);
|
||||
const result = await bridge.aiFetch(
|
||||
url,
|
||||
'GET',
|
||||
|
||||
@@ -1,13 +1,34 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { buildModelDiscoveryHeaders, resolveModelsDiscoveryEndpoint } from "./modelDiscoveryHeaders";
|
||||
import {
|
||||
buildModelDiscoveryHeaders,
|
||||
isCustomAnthropicBaseURL,
|
||||
resolveModelsDiscoveryEndpoint,
|
||||
} from "./modelDiscoveryHeaders";
|
||||
|
||||
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version for the anthropic family", () => {
|
||||
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test"), {
|
||||
"x-api-key": "sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
});
|
||||
test("buildModelDiscoveryHeaders uses x-api-key+anthropic-version only on official anthropic host", () => {
|
||||
for (const baseURL of [undefined, "", "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
|
||||
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
|
||||
"x-api-key": "sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
});
|
||||
assert.equal(isCustomAnthropicBaseURL(baseURL), false);
|
||||
}
|
||||
});
|
||||
|
||||
test("buildModelDiscoveryHeaders sends both x-api-key and Bearer auth on custom anthropic bases", () => {
|
||||
for (const baseURL of [
|
||||
"https://ark.cn-beijing.volces.com/api/plan",
|
||||
"https://gateway.example/v1",
|
||||
]) {
|
||||
assert.equal(isCustomAnthropicBaseURL(baseURL), true);
|
||||
assert.deepEqual(buildModelDiscoveryHeaders("anthropic", "sk-test", {}, baseURL), {
|
||||
"x-api-key": "sk-test",
|
||||
Authorization: "Bearer sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("buildModelDiscoveryHeaders uses Bearer auth for the openai-compatible family", () => {
|
||||
@@ -65,4 +86,16 @@ test('custom discovery headers override default auth regardless of case', () =>
|
||||
assert.equal(Object.keys(headers).filter(key => key.toLowerCase() === name.toLowerCase()).length, 1);
|
||||
assert.equal(headers['X-Tenant'], 'tenant');
|
||||
}
|
||||
|
||||
const customAnthropicAuth = buildModelDiscoveryHeaders(
|
||||
'anthropic',
|
||||
'default-key',
|
||||
{ authorization: 'Bearer custom-token' },
|
||||
'https://ark.cn-beijing.volces.com/api/plan',
|
||||
);
|
||||
assert.deepEqual(customAnthropicAuth, {
|
||||
'x-api-key': 'default-key',
|
||||
'anthropic-version': '2023-06-01',
|
||||
authorization: 'Bearer custom-token',
|
||||
});
|
||||
});
|
||||
@@ -27,11 +27,27 @@ export function resolveModelsDiscoveryEndpoint(
|
||||
return STYLE_DEFAULT_MODELS_ENDPOINT[style] ?? presetEndpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `baseURL` is a valid URL whose host is not the official
|
||||
* `api.anthropic.com` endpoint. Omitted or blank values default to the
|
||||
* official host and return `false`.
|
||||
*/
|
||||
export function isCustomAnthropicBaseURL(baseURL?: string): boolean {
|
||||
const trimmed = baseURL?.trim();
|
||||
if (!trimmed) return false;
|
||||
try {
|
||||
return new URL(trimmed).hostname.toLowerCase() !== "api.anthropic.com";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick auth headers for a provider's `/models` discovery endpoint.
|
||||
*
|
||||
* Each wire-protocol family uses its own auth dialect:
|
||||
* - `anthropic`: `x-api-key` + `anthropic-version`
|
||||
* - `anthropic`: `x-api-key` + `anthropic-version` on official `api.anthropic.com`;
|
||||
* custom Anthropic-compatible gateways also receive `Authorization: Bearer ...`
|
||||
* - `google`: `x-goog-api-key` (Google Generative AI rejects Bearer)
|
||||
* - `openai`: `Authorization: Bearer …` (also the OpenAI-compat default)
|
||||
*
|
||||
@@ -41,12 +57,16 @@ export function resolveModelsDiscoveryEndpoint(
|
||||
function buildDefaultModelDiscoveryHeaders(
|
||||
style: ProviderStyle,
|
||||
apiKey: string | undefined,
|
||||
baseURL?: string,
|
||||
): Record<string, string> {
|
||||
if (!apiKey) return {};
|
||||
switch (style) {
|
||||
case "anthropic":
|
||||
return {
|
||||
"x-api-key": apiKey,
|
||||
...(isCustomAnthropicBaseURL(baseURL)
|
||||
? { Authorization: `Bearer ${apiKey}` }
|
||||
: {}),
|
||||
"anthropic-version": "2023-06-01",
|
||||
};
|
||||
case "google":
|
||||
@@ -61,8 +81,9 @@ export function buildModelDiscoveryHeaders(
|
||||
style: ProviderStyle,
|
||||
apiKey: string | undefined,
|
||||
customHeaders: Record<string, string> = {},
|
||||
baseURL?: string,
|
||||
): Record<string, string> {
|
||||
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey);
|
||||
const headers = buildDefaultModelDiscoveryHeaders(style, apiKey, baseURL);
|
||||
const overridden = new Set(Object.keys(customHeaders).map((name) => name.toLowerCase()));
|
||||
return Object.fromEntries([
|
||||
...Object.entries(headers).filter(([name]) => !overridden.has(name.toLowerCase())),
|
||||
|
||||
@@ -59,17 +59,38 @@ test("validateProviderProbeInputs requires base URL and API key except for ollam
|
||||
);
|
||||
});
|
||||
|
||||
test("classifyProviderProbeResponse marks auth and transport failures as error", () => {
|
||||
test("classifyProviderProbeResponse marks auth, permission, server, and transport failures as error", () => {
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 401, latencyMs: 120, error: "Unauthorized" }).health,
|
||||
"error",
|
||||
);
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 403, latencyMs: 90 }).health,
|
||||
"error",
|
||||
);
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 502, latencyMs: 200 }).health,
|
||||
"error",
|
||||
);
|
||||
assert.equal(
|
||||
classifyProviderProbeResponse({ ok: false, status: 0, latencyMs: 30, error: "Request timeout" }).health,
|
||||
"error",
|
||||
);
|
||||
});
|
||||
|
||||
test("classifyProviderProbeResponse downgrades HTTP 404 models-list probe to warn", () => {
|
||||
const result = classifyProviderProbeResponse({
|
||||
ok: false,
|
||||
status: 404,
|
||||
latencyMs: 95,
|
||||
data: "404 page not found",
|
||||
});
|
||||
assert.equal(result.health, "warn");
|
||||
assert.equal(result.statusCode, 404);
|
||||
assert.equal(result.latencyMs, 95);
|
||||
assert.ok(result.error && result.error.includes("404"));
|
||||
});
|
||||
|
||||
test("classifyProviderProbeResponse marks 2xx with models payload as ok", () => {
|
||||
const result = classifyProviderProbeResponse({
|
||||
ok: true,
|
||||
@@ -188,11 +209,11 @@ test("probeProviderConnection returns typed failures before fetch", async () =>
|
||||
});
|
||||
|
||||
test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bases", async () => {
|
||||
const calls: string[] = [];
|
||||
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
|
||||
const run = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url) => {
|
||||
calls.push(url);
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
@@ -205,46 +226,90 @@ test("probeProviderConnection does not double /v1 for Anthropic AI SDK style bas
|
||||
providerId: "custom",
|
||||
style: "anthropic",
|
||||
});
|
||||
assert.deepEqual(calls, ["https://gateway.example/v1/models"]);
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
url: "https://gateway.example/v1/models",
|
||||
headers: {
|
||||
"x-api-key": "sk-test",
|
||||
Authorization: "Bearer sk-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.equal(run.ok, true);
|
||||
});
|
||||
|
||||
test("Volcengine Agent Plan OpenAI Detect distinguishes a missing catalog from a failed chat request", async () => {
|
||||
const calls: Array<{ url: string; method?: string }> = [];
|
||||
const run = (baseURL: string, status: number, style: "openai" | "anthropic" = "openai") =>
|
||||
probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, method) => {
|
||||
calls.push({ url, method });
|
||||
return { ok: false, status, data: "" };
|
||||
},
|
||||
},
|
||||
baseURL,
|
||||
apiKey: "fixture-key",
|
||||
providerId: "custom",
|
||||
style,
|
||||
now: () => 0,
|
||||
});
|
||||
test("probeProviderConnection keeps official Anthropic free of Bearer while custom gateways get Bearer and 404 warns", async () => {
|
||||
const calls: Array<{ url: string; headers?: Record<string, string> }> = [];
|
||||
|
||||
const base = "https://ark.cn-beijing.volces.com/api/plan/v3";
|
||||
const missingCatalog = await run(base + "/", 404);
|
||||
assert.deepEqual(missingCatalog, {
|
||||
ok: true,
|
||||
classification: { health: "warn", statusCode: 404, latencyMs: 0, notice: "model-list-unavailable" },
|
||||
const official = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
data: JSON.stringify({ data: [{ id: "claude-sonnet-4-5" }] }),
|
||||
};
|
||||
},
|
||||
},
|
||||
baseURL: "https://api.anthropic.com",
|
||||
apiKey: "sk-ant-test",
|
||||
providerId: "anthropic",
|
||||
style: "anthropic",
|
||||
});
|
||||
assert.equal(official.ok, true);
|
||||
assert.deepEqual(calls[0], {
|
||||
url: "https://api.anthropic.com/v1/models",
|
||||
headers: {
|
||||
"x-api-key": "sk-ant-test",
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
});
|
||||
|
||||
const agentPlanOpenAI = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
return { ok: false, status: 404, data: "404 page not found" };
|
||||
},
|
||||
},
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan/v3",
|
||||
apiKey: "ark-key",
|
||||
providerId: "custom",
|
||||
style: "openai",
|
||||
});
|
||||
assert.equal(agentPlanOpenAI.ok, true);
|
||||
if (!agentPlanOpenAI.ok) throw new Error("expected probe result");
|
||||
assert.equal(agentPlanOpenAI.classification.health, "warn");
|
||||
assert.equal(agentPlanOpenAI.classification.statusCode, 404);
|
||||
assert.deepEqual(calls[1], {
|
||||
url: "https://ark.cn-beijing.volces.com/api/plan/v3/models",
|
||||
headers: { Authorization: "Bearer ark-key" },
|
||||
});
|
||||
|
||||
const agentPlanAnthropic = await probeProviderConnection({
|
||||
bridge: {
|
||||
aiFetch: async (url, _method, headers) => {
|
||||
calls.push({ url, headers });
|
||||
return { ok: false, status: 404, data: "404 page not found" };
|
||||
},
|
||||
},
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
|
||||
apiKey: "ark-key",
|
||||
providerId: "custom",
|
||||
style: "anthropic",
|
||||
});
|
||||
assert.equal(agentPlanAnthropic.ok, true);
|
||||
if (!agentPlanAnthropic.ok) throw new Error("expected probe result");
|
||||
assert.equal(agentPlanAnthropic.classification.health, "warn");
|
||||
assert.equal(agentPlanAnthropic.classification.statusCode, 404);
|
||||
assert.deepEqual(calls[2], {
|
||||
url: "https://ark.cn-beijing.volces.com/api/plan/v1/models",
|
||||
headers: {
|
||||
"x-api-key": "ark-key",
|
||||
Authorization: "Bearer ark-key",
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
});
|
||||
assert.deepEqual(calls, [{ url: base + "/models", method: "GET" }]);
|
||||
for (const [url, status, style] of [
|
||||
[base, 401, "openai"],
|
||||
[base, 503, "openai"],
|
||||
[base, 404, "anthropic"],
|
||||
[base + "/typo", 404, "openai"],
|
||||
["https://ark.cn-beijing.volces.com/api/v3", 404, "openai"],
|
||||
["https://ark.cn-beijing.volces.com.evil.example/api/plan/v3", 404, "openai"],
|
||||
["https://example.test/api/plan/v3", 404, "openai"],
|
||||
] as const) {
|
||||
const result = await run(url, status, style);
|
||||
assert.ok(result.ok);
|
||||
assert.equal(result.classification.health, "error", `${url}: ${status} (${style})`);
|
||||
assert.equal(result.classification.notice, undefined);
|
||||
}
|
||||
});
|
||||
@@ -15,7 +15,6 @@ export type ProviderProbeClassification = {
|
||||
latencyMs: number;
|
||||
statusCode: number;
|
||||
modelCount?: number;
|
||||
notice?: "model-list-unavailable";
|
||||
error?: string;
|
||||
};
|
||||
|
||||
@@ -62,17 +61,6 @@ export function buildProviderProbeUrl(baseURL: string, endpoint: string): string
|
||||
return `${base}${path.startsWith("/") ? path : `/${path}`}`;
|
||||
}
|
||||
|
||||
function isVolcengineAgentPlanCatalog(url: string): boolean {
|
||||
try {
|
||||
const target = new URL(url);
|
||||
return target.origin === "https://ark.cn-beijing.volces.com"
|
||||
&& !target.username && !target.password && !target.search && !target.hash
|
||||
&& target.pathname === "/api/plan/v3/models";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateProviderProbeInputs(input: {
|
||||
baseURL: string;
|
||||
apiKey: string;
|
||||
@@ -110,7 +98,8 @@ function countModelsInPayload(data: string | undefined): number | undefined {
|
||||
|
||||
/**
|
||||
* Map a lightweight `/models` (or equivalent) probe response to green / yellow / red.
|
||||
* Yellow covers slow-but-successful replies and empty model catalogs.
|
||||
* Yellow covers slow-but-successful replies, empty model catalogs, and HTTP 404
|
||||
* (gateways that work for chat without exposing a models listing route).
|
||||
*/
|
||||
export function classifyProviderProbeResponse(input: {
|
||||
ok: boolean;
|
||||
@@ -127,6 +116,14 @@ export function classifyProviderProbeResponse(input: {
|
||||
...(input.error ? { error: input.error } : {}),
|
||||
};
|
||||
|
||||
if (input.status === 404) {
|
||||
return {
|
||||
...base,
|
||||
health: "warn",
|
||||
error: input.error || "Model list not available (HTTP 404)",
|
||||
};
|
||||
}
|
||||
|
||||
if (!input.ok || input.status < 200 || input.status >= 300) {
|
||||
return {
|
||||
...base,
|
||||
@@ -194,7 +191,12 @@ export async function probeProviderConnection(input: {
|
||||
await bridge.aiAllowlistAddHost(baseURL);
|
||||
}
|
||||
const url = buildProviderProbeUrl(baseURL, endpoint);
|
||||
const headers = buildModelDiscoveryHeaders(input.style, input.apiKey, input.customHeaders);
|
||||
const headers = buildModelDiscoveryHeaders(
|
||||
input.style,
|
||||
input.apiKey,
|
||||
input.customHeaders,
|
||||
baseURL,
|
||||
);
|
||||
const result = await bridge.aiFetch(
|
||||
url,
|
||||
"GET",
|
||||
@@ -205,21 +207,12 @@ export async function probeProviderConnection(input: {
|
||||
undefined,
|
||||
input.skipTLSVerify,
|
||||
);
|
||||
const latencyMs = Math.max(0, now() - startedAt);
|
||||
// The Agent Plan chat endpoint can work even when this catalog returns 404.
|
||||
// Do not reinterpret generic 404s, other protocols, or authentication errors.
|
||||
if (input.style === "openai" && !result.ok && result.status === 404 && isVolcengineAgentPlanCatalog(url)) {
|
||||
return {
|
||||
ok: true,
|
||||
classification: { health: "warn", statusCode: 404, latencyMs, notice: "model-list-unavailable" },
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
classification: classifyProviderProbeResponse({
|
||||
ok: result.ok,
|
||||
status: result.status ?? (result.ok ? 200 : 0),
|
||||
latencyMs,
|
||||
latencyMs: Math.max(0, now() - startedAt),
|
||||
data: result.data,
|
||||
error: result.error,
|
||||
slowThresholdMs: input.slowThresholdMs,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { wrapLanguageModel, type LanguageModelMiddleware } from 'ai';
|
||||
import type { ProviderConfig, ProviderStyle } from '../types';
|
||||
import { resolveOpenAIApi, resolveProviderStyle } from '../types';
|
||||
import { normalizeAnthropicSdkBaseURL } from '../anthropicCompatBaseUrl';
|
||||
import { isCustomAnthropicBaseURL } from '../modelDiscoveryHeaders';
|
||||
import { buildSdkRequestHeaders } from '../providerRequestHeaders';
|
||||
import { normalizeOllamaSdkBaseURL } from '../ollamaCompatBaseUrl';
|
||||
import { normalizeOpenAIChatCacheUsage } from '../openAIChatCacheUsage';
|
||||
@@ -774,13 +775,25 @@ function createProviderModel(
|
||||
: openai.chat(modelId);
|
||||
}
|
||||
|
||||
case 'anthropic':
|
||||
case 'anthropic': {
|
||||
// Official api.anthropic.com keeps x-api-key only. Custom Anthropic-compat
|
||||
// gateways (e.g. Volcengine Ark Agent Plan, Claude Code proxies) may require
|
||||
// Authorization: Bearer (ANTHROPIC_AUTH_TOKEN) or x-api-key, so send both.
|
||||
// @ai-sdk/anthropic rejects passing apiKey and authToken together, so pass
|
||||
// authToken for Bearer and retain x-api-key in headers unless overridden.
|
||||
const useCustomBearer = Boolean(apiKey && isCustomAnthropicBaseURL(baseURL));
|
||||
const hasCustomXApiKey = Object.keys(sdkHeaders).some(
|
||||
(key) => key.toLowerCase() === 'x-api-key',
|
||||
);
|
||||
return createAnthropic({
|
||||
apiKey,
|
||||
...(useCustomBearer ? { authToken: apiKey } : { apiKey }),
|
||||
baseURL,
|
||||
fetch: customFetch,
|
||||
headers: sdkHeaders,
|
||||
headers: useCustomBearer && !hasCustomXApiKey
|
||||
? { 'x-api-key': apiKey!, ...sdkHeaders }
|
||||
: sdkHeaders,
|
||||
})(modelId);
|
||||
}
|
||||
|
||||
case 'google':
|
||||
return createGoogle({
|
||||
|
||||
@@ -323,3 +323,75 @@ test("OpenAI Chat sends inline image attachments as data URLs through the bridge
|
||||
}
|
||||
assert.equal(requests.length, 4);
|
||||
});
|
||||
|
||||
test("Anthropic SDK sends x-api-key only on official host and adds Bearer on custom bases", async (t) => {
|
||||
const browserGlobal = globalThis as typeof globalThis & { window?: unknown };
|
||||
const originalWindow = browserGlobal.window;
|
||||
t.after(() => { browserGlobal.window = originalWindow; });
|
||||
const requests: Array<{ url: string; headers: Headers }> = [];
|
||||
Reflect.set(globalThis, "window", {
|
||||
netcatty: {
|
||||
aiFetch: async (url: string, _method: string, headers: Record<string, string>) => {
|
||||
requests.push({ url, headers: new Headers(headers) });
|
||||
return { ok: false, status: 400, data: '{"error":{"message":"captured anthropic request"}}' };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const prompt = [{ role: "user" as const, content: [{ type: "text" as const, text: "hello" }] }];
|
||||
|
||||
for (const baseURL of [undefined, "https://api.anthropic.com", "https://api.anthropic.com/v1"]) {
|
||||
const model = createModelFromConfig(makeConfig({
|
||||
providerId: "anthropic",
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL,
|
||||
}));
|
||||
await assert.rejects(async () => await model.doGenerate({ prompt }));
|
||||
const request = requests.at(-1)!;
|
||||
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
|
||||
assert.equal(request.headers.get("authorization"), null);
|
||||
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
|
||||
}
|
||||
|
||||
for (const baseURL of [
|
||||
"https://ark.cn-beijing.volces.com/api/plan",
|
||||
"https://gateway.example/v1",
|
||||
]) {
|
||||
const model = createModelFromConfig(makeConfig({
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL,
|
||||
}));
|
||||
await assert.rejects(async () => await model.doGenerate({ prompt }));
|
||||
const request = requests.at(-1)!;
|
||||
assert.equal(request.url, baseURL.endsWith("/api/plan")
|
||||
? baseURL + "/v1/messages"
|
||||
: baseURL + "/messages");
|
||||
assert.equal(request.headers.get("x-api-key"), "__IPC_SECURED__");
|
||||
assert.equal(request.headers.get("authorization"), "Bearer __IPC_SECURED__");
|
||||
assert.equal(request.headers.get("anthropic-version"), "2023-06-01");
|
||||
}
|
||||
|
||||
const overridden = createModelFromConfig(makeConfig({
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
|
||||
customHeaders: { Authorization: "Bearer custom-override" },
|
||||
}));
|
||||
await assert.rejects(async () => await overridden.doGenerate({ prompt }));
|
||||
const overriddenReq = requests.at(-1)!;
|
||||
assert.equal(overriddenReq.headers.get("x-api-key"), "__IPC_SECURED__");
|
||||
assert.equal(overriddenReq.headers.get("authorization"), "Bearer custom-override");
|
||||
|
||||
const overriddenApiKey = createModelFromConfig(makeConfig({
|
||||
style: "anthropic",
|
||||
apiKey: "test-key",
|
||||
baseURL: "https://ark.cn-beijing.volces.com/api/plan",
|
||||
customHeaders: { "X-API-Key": "custom-x-api-key" },
|
||||
}));
|
||||
await assert.rejects(async () => await overriddenApiKey.doGenerate({ prompt }));
|
||||
const overriddenApiKeyReq = requests.at(-1)!;
|
||||
assert.equal(overriddenApiKeyReq.headers.get("x-api-key"), "custom-x-api-key");
|
||||
assert.equal(overriddenApiKeyReq.headers.get("authorization"), "Bearer __IPC_SECURED__");
|
||||
});
|
||||
Reference in new issue
Block a user