mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-31 04:12:10 +03:00
* chore(release): open v3.8.27 development cycle * fix(security): polynomial ReDoS in comboAgentMiddleware regex (#3982) * fix(security): eliminate polynomial ReDoS in comboAgentMiddleware <omniModel> regex (CodeQL js/polynomial-redos) CACHE_TAG_PATTERN wrapped the tag in an unbounded `(?:\\n|\n|\r)*` prefix/suffix. On an unanchored `.test()`/`.exec()` that is O(n²) on inputs with many newlines (CodeQL js/polynomial-redos, alerts #612/#613). The surrounding runs are irrelevant to detecting/capturing the tag, so the detection pattern now matches only the core `<omniModel>([^<]+)</omniModel>`; the global strip pattern still consumes the wrapping newlines (combo.ts streaming, #531) but BOUNDED ({0,16}) so it stays linear. Behavior preserved: detection, model extraction, multi-tag stripping (#454) and blank-line cleanup all unchanged (107 related tests green). Adds ReDoS-safety regression tests (50k-newline inputs complete in <1ms). * docs(changelog): add #3982 ReDoS fix to [3.8.27] * ci(security): harden workflows — artipacked persist-credentials + cache-poisoning + SC2086 (#3965) * Refine provider quota card display (#3969) Integrated into release/v3.8.27 * feat: add sidebar group separator toggles (#3971) Integrated into release/v3.8.27 * Gate control-plane proxy direct fallback (#3963) Integrated into release/v3.8.27 * Capture actual upstream provider requests (#3941) Integrated into release/v3.8.27 * ci(quality): flip require-tighten + osv + Trivy to blocking (v3.8.27 cycle-end) (#3984) * fix(resilience): respect connection cooldown stored as numeric epoch (#3954) (#3995) rate_limited_until is a TEXT column, but setConnectionRateLimitUntil (Antigravity full-quota path) persists a raw epoch number that SQLite coerces to a numeric string ("1781696905131.0"). The selection predicate isAccountUnavailable then did new Date("1781696905131.0") -> NaN, so the cooling connection was never skipped and the router kept dispatching to rate-limited accounts. Normalize numeric-epoch strings (and number/Date/ISO) via a shared cooldownUntilMs() helper in isAccountUnavailable / getEarliestRateLimitedUntil / filterAvailableAccounts / parseFutureDateMs. ISO behavior preserved. * fix(providers): fetch live /models for LLM7 and BytePlus (#3976) (#3996) llm7 and byteplus carry a real modelsUrl but were not classified by any live-fetch branch of the model-import route, so their hardcoded 4-entry registry catalog was served (source local_catalog) instead of the upstream catalog. Add both to NAMED_OPENAI_STYLE_PROVIDERS so the route probes <baseUrl>/models and serves the live list, falling back to the local catalog only on fetch failure. * fix(dashboard): logs auto-refresh reads live visibility, not a stale mount ref (#3972) (#3997) The auto-refresh interval gated each tick on visibleRef, seeded once at mount and updated only by a visibilitychange event. A tab mounted while document.visibilityState is 'hidden' (background load, bfcache, embedded/proxied webviews) with no later visibilitychange left the ref false forever, so the interval ticked but never fetched — only the manual button worked. Read the live document.visibilityState in the tick instead. * feat(compression): add Indonesian caveman rules and language pack (#3975) Integrated into release/v3.8.27 (cherry picked from commitc9b5b1a892) * fix(combo): shuffle strict-random fallback remainder to spread load (#3959) (#3998) strict-random shuffled only the deck-selected slot 0 and left the fallback remainder in fixed priority order, so after a failing deck pick the chain always fell through to the same top-priority model — a persistently-failing model was retried on essentially every request and fallback load never spread across peers. Shuffle the remainder too (like the random strategy). * Add provider auth visibility controls (#3953) Integrated into release/v3.8.27 * fix(claude): forward client tool-search-tool anthropic-beta on the Claude OAuth path (#3974) (#3999) The client-negotiated anthropic-beta: tool-search-tool-2025-10-19 was dropped on both Claude code paths (default executor rebuilt from static ANTHROPIC_BETA_CLAUDE_OAUTH; selectBetaFlags only read the client beta to gate thinking/effort), so claude.ai rejected deferred-tool requests with 400 'Tool reference not found'. Add an allowlist-merge (mergeClientAnthropicBeta) that unions the client's allowlisted betas into the outbound set on both paths, preserving #3415 (no forced thinking/effort). * feat(providers): add model search filter to provider dashboard (#3950) Integrated into release/v3.8.27 * fix(vision-bridge): force bridge for tokenrouter deepseek models (#3946) Integrated into release/v3.8.27 * fix(executor): strip stream_options on non-streaming requests (#3884) (#4000) Clients that send stream_options:{include_usage:true} regardless of stream (e.g. the OpenAI Python SDK) had it passed through on non-streaming calls; NVIDIA NIM rejected it with 400 'Stream options can only be defined when stream=True'. DefaultExecutor.transformRequest only injected/cleared stream_options on the streaming branch and never stripped a client-sent value when stream=false. Add a !stream strip branch; the streaming injection path is unchanged. Global to openai-compat providers. * fix(qwen-web): cookie validation false-positive - check response body for user object (#3958) Integrated into release/v3.8.27 * fix(db): persist backup retention days (#3970) Integrated into release/v3.8.27 * 大量UI显示和i18n优化 (#3973) Integrated into release/v3.8.27 * deps: bump the npm_and_yarn group across 1 directory with 2 updates (#3943) Integrated into release/v3.8.27 * deps: bump form-data from 4.0.5 to 4.0.6 (#3944) Integrated into release/v3.8.27 * deps: bump vite from 8.0.5 to 8.0.16 (#3942) Integrated into release/v3.8.27 * chore(quality): re-baseline validation.ts 4407->4428 (#3958 qwen body-check) The qwen-web validation body-check merged in #3958 pushed validation.ts past its frozen size on the integrated release tip. Bump the baseline with justification; no logic is separately extractable from the existing qwen-web validation branch. * deps: bump the production group with 13 updates (#3915) Integrated into release/v3.8.27 — low-risk group (playwright 1.60→1.61 minor + transitive patches; fumadocs-core 16.9→16.10 minor). * chore(deps): ignore jscpd major bumps (v5 Rust rewrite breaks the duplication gate) Our duplication ratchet (scripts/check/check-duplication.mjs) is pinned to jscpd@4 and parses jscpd-report.json against a frozen baseline. jscpd v5 is a native Rust binary with no Node.js API and a different report/bin, so a major bump would break the gate. Migrate deliberately, not via dependabot. Closes the noise from #3916. * fix(perplexity-web): parse schematized diff_block stream so answers aren't empty (#4001) Integrated into release/v3.8.27 — schematized diff_block parsing follow-up to #3938. * refactor: modularize providerRegistry.ts into 159 individual provider plugins (#3993) Modularize provider registry (#3594). Integrated into release/v3.8.27 after rebase + behavior-preservation verification (provider-consistency gate 159/232/0, typecheck, registry tests, build 556/556). Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com> * fix(registry): restore byteplus + mimocode dropped by #3993 modularization The provider-registry modularization (#3993) was cut from a base predating the byteplus (#3877) and mimocode (#3837) registry entries, so merging it silently dropped both providers (getRegistryEntry returned undefined → validation reported 'not supported'). Re-add them as registry modules in the new structure; registered count 159→161, provider-consistency 161/232/0. Also align the pre-existing qwen-web validator test to #3958: since the validator now requires a real `user` object in the 200 body, the mock must carry one. * refactor: modularize schemas (non-stacked) (#3988) Modularize validation schemas (#3594). Integrated into release/v3.8.27 after rebase (reconciled the merged hiddenSidebarGroupLabels #3971 + intelligenceSyncRequestSchema into the new modules) + behavior verification (typecheck, 195 schema/settings/validation tests, build 556/556). Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com> * fix(default-executor): honor custom providerSpecificData.baseUrl for OpenAI-format providers (#4002) Integrated into release/v3.8.27 — honor custom providerSpecificData.baseUrl in DefaultExecutor (openai-format), tested. * feat(openai): honor custom base URL in model discovery + complete openai/codex pricing (#4005) Integrated into release/v3.8.27 — openai model-discovery honors custom base URL (SSRF-guarded) + pricing rows for new openai/codex models. Tested + baselines bumped. * fix(live-ws): bridge sidecar events to dashboard (#4004) Integrated into release/v3.8.27 — repair LiveWS sidecar (startup, same-origin /live-ws, main→sidecar compression.completed bridge, early-msg queue). Fixed the cookie-parse regex (\s) + added a focused unit test; baseline bumped for the non-blocking chatCore bridge. * docs(troubleshooting): note MITM proxy cannot intercept Windows-host apps under WSL (#4003) Integrated into release/v3.8.27 — MITM/WSL troubleshooting note. * fix(repo): untrack accidentally-committed root node_modules symlink + gitignore it A worktree node_modules symlink (-> the main checkout's node_modules) was staged by a `git add -A` during the #3988 merge and committed into05213ac6a. The symlink points at the repo's own node_modules path, so checking it out turns the main checkout's node_modules into a self-referential symlink (breaking tsx/all node ops). Untrack it and add a root-anchored /node_modules ignore so the symlink form can't be re-committed (the existing 'node_modules/' only matches directories). * fix(quality): allowlist socks dep (declared by #4004, never allowlisted) socks@^2.8.7 was added to package.json in #4004 (LiveWS sidecar,02302131f) as a phantom-dep cleanup but never added to dependency-allowlist.json, so check:deps has been red on the release tip ever since. socks is the standard SOCKS proxy client (dep of fetch-socks), legitimate and years old. * feat(sse): real LLMLingua-2 ONNX compression engine (stable) (#4014) Integrated into release/v3.8.27. Adjustments before merge: - Synced with the current release tip (was 11 commits behind). - Added the 3 LLMLingua-2 ONNX optional-runtime deps to dependency-allowlist.json (@atjsh/llmlingua-2, @tensorflow/tfjs, js-tiktoken) — the only gate that was red. - socks was allowlisted directly on release (separate fix d7db5c73d; it was declared by #4004 but never allowlisted, leaving check:deps red release-wide). Verified locally: check:deps OK, file-size OK, public-creds OK, provider-consistency 161/232/0, typecheck:core clean, 24/24 LLMLingua tests pass. The only remaining Fast-QG red is the pre-existing #3972 orphan test (request-logger-autorefresh-visibility-3972.test.tsx), which is release-wide and unrelated to this PR. * test(dashboard): rehome #3972 logs auto-refresh test so a runner collects it tests/unit/request-logger-autorefresh-visibility-3972.test.tsx (added by #3972 via #3997) sat at the top level of tests/unit/ as a .tsx vitest test, which NO runner collects: the node runner only globs *.test.ts, and test:vitest:ui only runs tests/unit/ui. So the #3972 regression guard never executed in CI and check:test-discovery was red release-wide. Move it under tests/unit/ui/ (the collected vitest:ui path) and fix the relative import depth. Verified: the test now runs and passes (2/2), and check:test-discovery is green. * feat(compression): capture per-engine analytics (#3960) + Lite schema fix (#3952) (#4018) Captures the net-new value from #3960 (per-engine breakdown analytics) and #3952 (Lite engine schema fix) onto release/v3.8.27. Fast QG green; 622/622 compression+analytics tests pass. * fix(sse): guard model-less registry entries in getUnsupportedParams (mimocode) (#4015) Real bugfix: guard model-less registry entries (mimocode) in getUnsupportedParams so handleChatCore no longer throws 'entry.models is not iterable' / reports 'All models failed' for unrelated requests. Includes a regression test. Fast QG green. * feat(ci): Quality Gate v2 — Onda 0 + Onda 1 (gate flips, TIA, SAST, DAST-smoke, mutation infra) (#4016) * docs(ops): add quality-gate assessment + replication playbook (Fase 9 foundation) * feat(ci): flip oasdiff breaking-change gate to blocking (ratchet) * docs(ops): deliver main branch-protection ruleset for owner to apply * fix(ci): run typecheck:core in PR->release fast-gates (close fast-gates hole, part 1) * perf(mutation): enable Stryker incremental mode + cache (scales the 60/80 rollout) * feat(ci): commit CodeQL advanced config (security-extended), replacing default-setup * feat(ci): version semgrep SAST workflow (owasp/secrets), advisory * feat(quality): TIA test-impact map builder (import-graph; map built at runtime, gitignored) * feat(quality): TIA impacted-test selector with run-all fail-safe * fix(ci): run TIA-impacted unit tests in PR->release fast-gates (build map at runtime, fail-safe full) * feat(ci): DAST-smoke per-PR (schemathesis subset + promptfoo injection-guard, blocking) * fix(ci): unbreak Fase 9 PR CI (MDX frontmatter, CodeQL conflict, dast-smoke advisory) - Add MDX frontmatter to docs/ops/{BRANCH_PROTECTION_MAIN,QUALITY_GATE_PLAYBOOK}.md. fumadocs rejects frontmatter-less docs -> 'npm run build' failed -> broke dast-smoke's build step (the release fast-gates never runs build, so this only surfaced on the PR). - codeql.yml: workflow_dispatch-only until the owner switches repo CodeQL Default->Advanced (advanced configs cannot be processed while default setup is enabled; documented inline). - dast-smoke.yml: job-level continue-on-error (advisory) so this brand-new gate matures before it blocks (repo convention: advisory -> blocking). * ci(quality): make TIA unit-test step advisory until release test-debt is cleared release/v3.8.27 carries ~17 pre-existing failing unit tests (budget #3537, apiKey #3552, several Zod schemas, Puter/Qwen executors, mimocode entry, etc.) unrelated to this PR — the new 'run tests on PR->release' gate surfaced them. Per the repo's advisory->blocking convention, this step enters advisory (it still runs + reports) so pre-existing debt doesn't block the gate program. typecheck:core stays blocking. Flip to blocking (remove continue-on-error) once the release suite is green. * fix(sse): preserve Kiro streaming finish_reason tool_calls (#3980) (#4025) * fix(guardrails): preserve original image when vision-bridge describe fails (#4012) (#4026) * feat(api): advertise combo capabilities on import surfaces (#3979) (#4027) * feat(sse): delegated Anthropic Context Editing for Claude (clear_tool_uses) (#4021) Opt-in Claude-only delegated compression: injects context_management.clear_tool_uses_20250919 at the Claude pre-serialization chokepoint (composes with clear_thinking, thinking first), threaded via ExecuteInput from handleChatCore. Pure edit-builder + 11 tests (7 unit + 4 e2e fetch-capture). Beta context-management-2025-06-27 already advertised; allowlist done. Telemetry/400-fallback/claude-web coverage deferred. * fix(opencode): map x-session-affinity to x-opencode-session for custom providers (#4022) (#4028) * fix(dashboard): Playground Compare tab loading + HTTP method guard (#4024) randomUUID non-HTTPS fallback + static CompareTab import; raw HTTP TRACE->405 method guard wired into dev + standalone servers. Integrated into release/v3.8.27. * refactor(dashboard): settings UI layout + API Keys naming (#4020) Presentation/relabel refactor of the Settings dashboard (API Manager -> API Keys), card relocations, Toggle adoption, present-but-disabled engine steps. Auth-file changes are string/comment-only (no behavior change). Integrated into release/v3.8.27. * fix: restore unit regressions dropped by lossy schema/registry modularizations (#4030) Restores schema fields (combo reasoningTokenBuffer, budget-0 #3537, openrouter preset, proxy family #3777, resilience degradation/providerCooldown), qwen-web v2 endpoint+catalog, mimocode models key — all dropped by #3988/#3993 — and aligns 3 tests to #3941/#3993. Verified: 8 failing regression tests on release tip -> 131/131 green on this branch. Integrated into release/v3.8.27. * fix(api): return 400 (not 500) for malformed JSON on /api/auth/login (#4031) Wrap request.json() so a malformed/non-JSON login body returns a structured 400 instead of falling through to the 500 catch. Fixes the schemathesis high-risk-endpoint DAST finding (verified: schemathesis step now passes). +TDD test. Integrated into release/v3.8.27. * feat(dashboard): real circuit-breaker state in the Combo Live cascade (U1b) (#4029) Overlays real provider circuit-breaker state (GET /api/monitoring/health) onto the Combo Live cascade as a 'CB: OPEN · 41s' badge. Pure enrichRunWithBreakers + fail-soft useProviderBreakerHealth poll; graceful when health is absent. +13 tests. Integrated into release/v3.8.27. * Fix promptfoo security assertion parsing (#4032) * chore(deps): dependabot security bumps + drop unused gray-matter (#4036) Integrated into release/v3.8.27 — dependabot security bumps (form-data/js-yaml/protobufjs/dompurify/hono) + drop unused gray-matter. Unblocks the npm audit:deps gate (Lint) branch-wide. * fix(ci): scope TIA to node:test unit files only (mirror test:unit glob) (#4035) Integrated into release/v3.8.27 — scopes the advisory TIA step to the test:unit node:test glob, fixing the 99 false failures. +4 TDD. * Refine compression settings, storage labels, and sidebar grouping (#4033) Integrated into release/v3.8.27 — relocate Token Saver into Compression Settings (controlled component), reorder Security/Authz tabs, storage labels + i18n relabel. Thanks @rdself! * [codex] add per-key local usage command (#4034) Integrated into release/v3.8.27 — per-key local @@om-usage command (cached quota, no upstream routing). Rebased onto modularized schemas/keys.ts + file-size rebaseline. Thanks @Witroch4! * chore(release): reconcile v3.8.27 CHANGELOG + i18n mirrors * ci(quality): unblock v3.8.27 release gates (zizmor pin + test-masking allowlist) - zizmor ratchet (151→139, no regression): SHA-pin every action ref ADDED this cycle — codeql/dast-smoke/semgrep (3 new workflows) + trivy-action (docker-publish) + actions/cache (nightly-mutation). Pre-existing tag refs keep the repo convention. - test-masking: add config/quality/test-masking-allowlist.json + allowlist support in check-test-masking.mjs (exempts ONLY the net-assert-reduction signal; tautology/skip/ deletion still fire). Allowlists 2 verified-legitimate reductions: appearance-widget-settings-schema (#4033 removed showTokenSaverOnEndpoint field) and dashboard-shell-tabs (#3973 tabs→redirect refactor, asserts replaced). +4 gate tests. * test(quality): reword test-masking self-test comments to avoid literal masking patterns The added allowlist-test comments contained the literal strings 'assert.ok(true)' and '.skip' which the masking detector's own regexes match as text — making the gate flag its own test file (net +1 tautology/skip/extended-tautology vs main). Reworded to plain prose ('a new tautology', 'a new skip marker'); test logic unchanged (24/24 pass). * fix(quality): unblock v3.8.27 release — align 3 stale tests + restore modularized settings-schema parity Release-PR full CI surfaced 3 deterministic test failures (no live product regression), all stale vs legitimate cycle changes: - settings-schema parity (#3988): the modularized updateSettingsSchema barrel (schemas/settings.ts) had diverged from the canonical settingsSchemas.ts (45 vs 85 fields — 40 dropped + 6 extra), a lossy-modularization dead-code copy. Re-export from the canonical source so the barrel can never diverge again (runtime already uses canonical). Parity test now passes. - api-manager permissions modal: #4034 added a 4th self-service switch (per-key usage allowance); a11y invariant (every switch type="button") still holds. Updated the static count 3 -> 4. - pack-artifact policy: dist/http-method-guard.cjs became a required runtime path; added it to the test's expected missing-paths list. Also documents the gate gap for Fase 9 (QUALITY_GATE_PLAYBOOK Parte 6): G1 run the deterministic unit layer + test-masking on PR->release (not just PR->main), G2 a modularization-parity gate (would have caught the #3988 drop at its PR), G3 flake quarantine. Env flakes (LiveWS startup timeout, integration server-startup cascade) are pre-existing/CI-env, triaged separately. --------- Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: Veier04 <118300867+Veier04@users.noreply.github.com> Co-authored-by: Felipe Sartori <felipesartori.ti@gmail.com> Co-authored-by: WormAlien <164898390+WormAlien@users.noreply.github.com> Co-authored-by: thezukiru <121331256+thezukiru@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: NOXX - Commiter <artur1992123@mail.ru> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: Demiurge The Single <megamen932@gmail.com> Co-authored-by: Witroch4 <witalo_rocha@hotmail.com>
1339 lines
46 KiB
TypeScript
1339 lines
46 KiB
TypeScript
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
|
|
import {
|
|
applyConfiguredUserAgent,
|
|
BaseExecutor,
|
|
getCustomUserAgent,
|
|
mergeAbortSignals,
|
|
mergeUpstreamExtraHeaders,
|
|
setUserAgentHeader,
|
|
} from "../../open-sse/executors/base.ts";
|
|
import { DefaultExecutor } from "../../open-sse/executors/default.ts";
|
|
import { PROVIDERS } from "../../open-sse/config/constants.ts";
|
|
import {
|
|
CLAUDE_CODE_COMPATIBLE_ANTHROPIC_VERSION,
|
|
CLAUDE_CODE_COMPATIBLE_DEFAULT_CHAT_PATH,
|
|
CLAUDE_CODE_COMPATIBLE_REDACT_THINKING_BETA,
|
|
CONTEXT_1M_BETA_HEADER,
|
|
} from "../../open-sse/services/claudeCodeCompatible.ts";
|
|
import { runWithCapture } from "../../open-sse/utils/providerRequestLogging.ts";
|
|
|
|
class TestExecutor extends BaseExecutor {
|
|
constructor(config = {}) {
|
|
super("test-provider", {
|
|
baseUrls: [
|
|
"https://primary.example/v1/chat/completions",
|
|
"https://fallback.example/v1/chat/completions",
|
|
],
|
|
headers: { "X-Test-Header": "base" },
|
|
...config,
|
|
});
|
|
}
|
|
|
|
async transformRequest(model, body, stream) {
|
|
return { ...body, transformed: true, model, stream };
|
|
}
|
|
}
|
|
|
|
test("BaseExecutor: openai-compatible buildUrl sanitizes custom chat paths", () => {
|
|
const executor = new BaseExecutor("openai-compatible-test", {});
|
|
const valid = executor.buildUrl("gpt-4.1", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://proxy.example/v1/",
|
|
chatPath: "/custom/chat/completions",
|
|
},
|
|
});
|
|
const invalid = executor.buildUrl("gpt-4.1", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://proxy.example/v1/",
|
|
chatPath: "../evil",
|
|
},
|
|
});
|
|
const invalidNullByte = executor.buildUrl("gpt-4.1", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://proxy.example/v1/",
|
|
chatPath: "/ok\0evil",
|
|
},
|
|
});
|
|
|
|
assert.equal(valid, "https://proxy.example/v1/custom/chat/completions");
|
|
assert.equal(invalid, "https://proxy.example/v1/chat/completions");
|
|
assert.equal(invalidNullByte, "https://proxy.example/v1/chat/completions");
|
|
});
|
|
|
|
test("BaseExecutor: legacy openai-compatible providers honor providerSpecificData.apiType", () => {
|
|
const executor = new BaseExecutor("openai-compatible-sp-openai", {});
|
|
const url = executor.buildUrl("gpt-5.4", true, 0, {
|
|
providerSpecificData: {
|
|
apiType: "responses",
|
|
baseUrl: "https://proxy.example/v1/",
|
|
},
|
|
});
|
|
|
|
assert.equal(url, "https://proxy.example/v1/responses");
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl handles Gemini, Claude and Qwen variants", () => {
|
|
const gemini = new DefaultExecutor("gemini");
|
|
const claude = new DefaultExecutor("claude");
|
|
const qwen = new DefaultExecutor("qwen");
|
|
|
|
assert.equal(
|
|
gemini.buildUrl("gemini-2.5-flash", false),
|
|
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent"
|
|
);
|
|
assert.equal(
|
|
gemini.buildUrl("gemini-2.5-flash", true),
|
|
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
|
);
|
|
assert.equal(claude.buildUrl("claude-sonnet-4", true), `${PROVIDERS.claude.baseUrl}?beta=true`);
|
|
assert.equal(qwen.buildUrl("qwen3-coder", true), "https://portal.qwen.ai/v1/chat/completions");
|
|
assert.equal(
|
|
qwen.buildUrl("qwen3-coder", true, 0, {
|
|
providerSpecificData: { resourceUrl: "custom.qwen.ai" },
|
|
}),
|
|
"https://custom.qwen.ai/v1/chat/completions"
|
|
);
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl uses full chat endpoints for hosted OpenAI-compatible providers", () => {
|
|
const bazaarlink = new DefaultExecutor("bazaarlink");
|
|
const crof = new DefaultExecutor("crof");
|
|
|
|
assert.equal(
|
|
bazaarlink.buildUrl("auto:free", true),
|
|
"https://bazaarlink.ai/api/v1/chat/completions"
|
|
);
|
|
assert.equal(crof.buildUrl("gpt-4.1", true), "https://crof.ai/v1/chat/completions");
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl honors a custom providerSpecificData.baseUrl for the built-in openai provider", () => {
|
|
const openai = new DefaultExecutor("openai");
|
|
|
|
// No override → hardcoded OpenAI endpoint (unchanged behavior).
|
|
assert.equal(
|
|
openai.buildUrl("gpt-4o", true),
|
|
"https://api.openai.com/v1/chat/completions"
|
|
);
|
|
|
|
// Custom base URL (e.g. a proxy/gateway) must be used instead of api.openai.com.
|
|
assert.equal(
|
|
openai.buildUrl("gpt-4o", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://api.contactboxtools.me/v1" },
|
|
}),
|
|
"https://api.contactboxtools.me/v1/chat/completions"
|
|
);
|
|
|
|
// Trailing slash is normalized.
|
|
assert.equal(
|
|
openai.buildUrl("gpt-4o", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1/" },
|
|
}),
|
|
"https://proxy.example/v1/chat/completions"
|
|
);
|
|
|
|
// A base URL already pointing at the chat endpoint is kept as-is.
|
|
assert.equal(
|
|
openai.buildUrl("gpt-4o", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1/chat/completions" },
|
|
}),
|
|
"https://proxy.example/v1/chat/completions"
|
|
);
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl handles openai-compatible and anthropic-compatible providers", () => {
|
|
const openAICompat = new DefaultExecutor("openai-compatible-test");
|
|
const openAIResponsesCompat = new DefaultExecutor("openai-compatible-responses-test");
|
|
const openAILegacyResponsesCompat = new DefaultExecutor("openai-compatible-sp-openai");
|
|
const anthropicCompat = new DefaultExecutor("anthropic-compatible-test");
|
|
const anthropicCcCompat = new DefaultExecutor("anthropic-compatible-cc-test");
|
|
|
|
assert.equal(
|
|
openAICompat.buildUrl("gpt-4.1", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1/" },
|
|
}),
|
|
"https://proxy.example/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
openAICompat.buildUrl("gpt-4.1", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://proxy.example/v1/",
|
|
chatPath: "/custom/chat",
|
|
},
|
|
}),
|
|
"https://proxy.example/v1/custom/chat"
|
|
);
|
|
assert.equal(
|
|
openAIResponsesCompat.buildUrl("gpt-4.1", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1/" },
|
|
}),
|
|
"https://proxy.example/v1/responses"
|
|
);
|
|
assert.equal(
|
|
openAILegacyResponsesCompat.buildUrl("gpt-5.4", true, 0, {
|
|
providerSpecificData: {
|
|
apiType: "responses",
|
|
baseUrl: "https://proxy.example/v1/",
|
|
},
|
|
}),
|
|
"https://proxy.example/v1/responses"
|
|
);
|
|
assert.equal(
|
|
anthropicCompat.buildUrl("claude-sonnet-4", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://anthropic.example/v1/" },
|
|
}),
|
|
"https://anthropic.example/v1/messages"
|
|
);
|
|
assert.equal(
|
|
anthropicCompat.buildUrl("claude-sonnet-4", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://anthropic.example/v1/",
|
|
chatPath: "/custom/messages",
|
|
},
|
|
}),
|
|
"https://anthropic.example/v1/custom/messages"
|
|
);
|
|
assert.equal(
|
|
anthropicCcCompat.buildUrl("claude-sonnet-4", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://cc.example/v1/messages",
|
|
},
|
|
}),
|
|
`https://cc.example${CLAUDE_CODE_COMPATIBLE_DEFAULT_CHAT_PATH}`
|
|
);
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl normalizes configurable chat-openai-compat base URLs", () => {
|
|
const bailian = new DefaultExecutor("bailian-coding-plan");
|
|
const heroku = new DefaultExecutor("heroku");
|
|
const databricks = new DefaultExecutor("databricks");
|
|
const azureAi = new DefaultExecutor("azure-ai");
|
|
const watsonx = new DefaultExecutor("watsonx");
|
|
const oci = new DefaultExecutor("oci");
|
|
const sap = new DefaultExecutor("sap");
|
|
const modal = new DefaultExecutor("modal");
|
|
const reka = new DefaultExecutor("reka");
|
|
const maritalk = new DefaultExecutor("maritalk");
|
|
const snowflake = new DefaultExecutor("snowflake");
|
|
const gigachat = new DefaultExecutor("gigachat");
|
|
const siliconflow = new DefaultExecutor("siliconflow");
|
|
|
|
assert.equal(
|
|
bailian.buildUrl("qwen3-coder-plus", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1",
|
|
},
|
|
}),
|
|
"https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1/messages"
|
|
);
|
|
assert.equal(
|
|
heroku.buildUrl("claude-4-sonnet", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://us.inference.heroku.com" },
|
|
}),
|
|
"https://us.inference.heroku.com/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
databricks.buildUrl("databricks-gpt-5", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://adb-1234567890123456.7.azuredatabricks.net/serving-endpoints",
|
|
},
|
|
}),
|
|
"https://adb-1234567890123456.7.azuredatabricks.net/serving-endpoints/chat/completions"
|
|
);
|
|
|
|
assert.equal(
|
|
azureAi.buildUrl("DeepSeek-V3.1", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://my-foundry.services.ai.azure.com" },
|
|
}),
|
|
"https://my-foundry.services.ai.azure.com/openai/v1/chat/completions"
|
|
);
|
|
|
|
assert.equal(
|
|
watsonx.buildUrl("ibm/granite-3-3-8b-instruct", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://ca-tor.ml.cloud.ibm.com" },
|
|
}),
|
|
"https://ca-tor.ml.cloud.ibm.com/ml/gateway/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
oci.buildUrl("openai.gpt-oss-20b", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://inference.generativeai.us-ashburn-1.oci.oraclecloud.com",
|
|
},
|
|
}),
|
|
"https://inference.generativeai.us-ashburn-1.oci.oraclecloud.com/openai/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
sap.buildUrl("gpt-4o", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://sap.example.com/v2/lm/deployments/demo-deployment",
|
|
},
|
|
}),
|
|
"https://sap.example.com/v2/lm/deployments/demo-deployment/chat/completions"
|
|
);
|
|
assert.equal(
|
|
modal.buildUrl("Qwen/Qwen3-4B-Thinking-2507-FP8", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://alice--demo.modal.run/v1",
|
|
},
|
|
}),
|
|
"https://alice--demo.modal.run/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
reka.buildUrl("reka-core", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://api.reka.ai/v1",
|
|
},
|
|
}),
|
|
"https://api.reka.ai/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
maritalk.buildUrl("sabia-4", true, 0, {
|
|
providerSpecificData: {
|
|
baseUrl: "https://chat.maritaca.ai/api/chat/inference",
|
|
},
|
|
}),
|
|
"https://chat.maritaca.ai/api/chat/completions"
|
|
);
|
|
assert.equal(
|
|
snowflake.buildUrl("llama3.3-70b", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://account.snowflakecomputing.com" },
|
|
}),
|
|
"https://account.snowflakecomputing.com/api/v2/cortex/inference:complete"
|
|
);
|
|
assert.equal(
|
|
gigachat.buildUrl("GigaChat-2-Pro", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://gigachat.devices.sberbank.ru/api/v1" },
|
|
}),
|
|
"https://gigachat.devices.sberbank.ru/api/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
siliconflow.buildUrl("deepseek-ai/DeepSeek-V3.2", true),
|
|
"https://api.siliconflow.com/v1/chat/completions"
|
|
);
|
|
assert.equal(
|
|
siliconflow.buildUrl("deepseek-ai/DeepSeek-V3.2", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://api.siliconflow.cn/v1" },
|
|
}),
|
|
"https://api.siliconflow.cn/v1/chat/completions"
|
|
);
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl falls back to OpenAI config for unknown providers", () => {
|
|
const executor = new DefaultExecutor("unknown-provider");
|
|
assert.equal(executor.config.baseUrl, PROVIDERS.openai.baseUrl);
|
|
assert.equal(executor.buildUrl("gpt-4.1", true), PROVIDERS.openai.baseUrl);
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl applies urlSuffix for zai and glm-coding-apikey", () => {
|
|
const zai = new DefaultExecutor("zai");
|
|
const glmCodingApikey = new DefaultExecutor("glm-coding-apikey");
|
|
assert.equal(
|
|
zai.buildUrl("glm-5", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://api.z.ai/api/anthropic/v1/messages" },
|
|
}),
|
|
"https://api.z.ai/api/anthropic/v1/messages?beta=true"
|
|
);
|
|
assert.equal(
|
|
glmCodingApikey.buildUrl("glm-4.7", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://api.z.ai/api/anthropic/v1/messages" },
|
|
}),
|
|
"https://api.z.ai/api/anthropic/v1/messages?beta=true"
|
|
);
|
|
assert.equal(zai.buildUrl("glm-5", true), "https://api.z.ai/api/anthropic/v1/messages?beta=true");
|
|
});
|
|
|
|
test("DefaultExecutor.buildUrl applies urlSuffix from registry for unknown providers with suffix", () => {
|
|
const executor = new DefaultExecutor("unknown-provider");
|
|
assert.equal(executor.buildUrl("gpt-4.1", true), PROVIDERS.openai.baseUrl);
|
|
});
|
|
|
|
test("DefaultExecutor.buildHeaders uses x-api-key for zai and glm-coding-apikey", () => {
|
|
const zai = new DefaultExecutor("zai");
|
|
const glmCodingApikey = new DefaultExecutor("glm-coding-apikey");
|
|
const zaiHeaders = zai.buildHeaders({ apiKey: "zai-key" }, true);
|
|
const glmHeaders = glmCodingApikey.buildHeaders({ apiKey: "glm-key" }, true);
|
|
assert.equal(zaiHeaders["x-api-key"], "zai-key");
|
|
assert.equal(glmHeaders["x-api-key"], "glm-key");
|
|
assert.equal(zaiHeaders["Authorization"], undefined);
|
|
assert.equal(glmHeaders["Authorization"], undefined);
|
|
});
|
|
|
|
test("DefaultExecutor.buildHeaders handles Gemini and Claude auth modes", () => {
|
|
const gemini = new DefaultExecutor("gemini");
|
|
const claude = new DefaultExecutor("claude");
|
|
const azureAi = new DefaultExecutor("azure-ai");
|
|
const oci = new DefaultExecutor("oci");
|
|
const sap = new DefaultExecutor("sap");
|
|
const modal = new DefaultExecutor("modal");
|
|
const maritalk = new DefaultExecutor("maritalk");
|
|
|
|
const geminiApiKeyHeaders = gemini.buildHeaders({ apiKey: "gem-key" }, true);
|
|
const geminiOAuthHeaders = gemini.buildHeaders({ accessToken: "gem-token" }, false);
|
|
const claudeApiKeyHeaders = claude.buildHeaders({ apiKey: "claude-key" }, true);
|
|
const claudeOAuthHeaders = claude.buildHeaders({ accessToken: "claude-token" }, false);
|
|
const azureAiHeaders = azureAi.buildHeaders({ apiKey: "azure-ai-key" }, true);
|
|
const ociHeaders = oci.buildHeaders(
|
|
{
|
|
apiKey: "oci-key",
|
|
projectId: "ocid1.generativeaiproject.oc1.us-chicago-1.example",
|
|
},
|
|
true
|
|
);
|
|
const sapHeaders = sap.buildHeaders(
|
|
{
|
|
apiKey: "sap-key",
|
|
providerSpecificData: {
|
|
resourceGroup: "shared",
|
|
},
|
|
},
|
|
true
|
|
);
|
|
const modalHeaders = modal.buildHeaders(
|
|
{
|
|
apiKey: "modal-key",
|
|
},
|
|
true
|
|
);
|
|
const maritalkHeaders = maritalk.buildHeaders({ apiKey: "maritalk-key" }, true);
|
|
|
|
assert.equal(geminiApiKeyHeaders["x-goog-api-key"], "gem-key");
|
|
assert.equal(geminiApiKeyHeaders.Accept, "text/event-stream");
|
|
assert.equal(geminiApiKeyHeaders.Authorization, undefined);
|
|
assert.equal(geminiOAuthHeaders.Authorization, "Bearer gem-token");
|
|
assert.equal(claudeApiKeyHeaders["x-api-key"], "claude-key");
|
|
assert.equal(claudeApiKeyHeaders.Accept, "text/event-stream");
|
|
assert.equal(claudeOAuthHeaders.Authorization, "Bearer claude-token");
|
|
assert.equal(claudeOAuthHeaders["x-api-key"], undefined);
|
|
assert.equal(azureAiHeaders["api-key"], "azure-ai-key");
|
|
assert.equal(azureAiHeaders.Authorization, undefined);
|
|
assert.equal(ociHeaders.Authorization, "Bearer oci-key");
|
|
assert.equal(ociHeaders["OpenAI-Project"], "ocid1.generativeaiproject.oc1.us-chicago-1.example");
|
|
assert.equal(sapHeaders.Authorization, "Bearer sap-key");
|
|
assert.equal(sapHeaders["AI-Resource-Group"], "shared");
|
|
assert.equal(modalHeaders.Authorization, "Bearer modal-key");
|
|
assert.equal(maritalkHeaders.Authorization, "Key maritalk-key");
|
|
});
|
|
|
|
test("DefaultExecutor.buildHeaders handles GLM, default auth and anthropic-compatible headers", () => {
|
|
const glm = new DefaultExecutor("glm");
|
|
const glmt = new DefaultExecutor("glmt");
|
|
const openai = new DefaultExecutor("openai");
|
|
const anthropicCompat = new DefaultExecutor("anthropic-compatible-test");
|
|
|
|
const glmHeaders = glm.buildHeaders({ accessToken: "glm-token" }, false);
|
|
const glmtHeaders = glmt.buildHeaders({ apiKey: "glmt-key" }, false);
|
|
const openaiHeaders = openai.buildHeaders({ apiKey: "sk-openai" }, true);
|
|
const anthropicHeaders = anthropicCompat.buildHeaders({ apiKey: "anth-key" }, true);
|
|
|
|
assert.equal(glmHeaders["x-api-key"], "glm-token");
|
|
assert.equal(glmtHeaders["x-api-key"], "glmt-key");
|
|
assert.equal(openaiHeaders.Authorization, "Bearer sk-openai");
|
|
assert.equal(openaiHeaders.Accept, "text/event-stream");
|
|
assert.equal(anthropicHeaders["x-api-key"], "anth-key");
|
|
assert.equal(anthropicHeaders["anthropic-version"], "2023-06-01");
|
|
assert.equal(anthropicHeaders.Accept, "text/event-stream");
|
|
});
|
|
|
|
test("DefaultExecutor local OpenAI-style providers honor custom base URLs and skip empty bearer headers", () => {
|
|
const lmStudio = new DefaultExecutor("lm-studio");
|
|
const vllm = new DefaultExecutor("vllm");
|
|
|
|
const lmStudioUrl = lmStudio.buildUrl("local-model", true, 0, {
|
|
providerSpecificData: { baseUrl: "http://127.0.0.1:4321/v1" },
|
|
});
|
|
const vllmHeaders = vllm.buildHeaders({}, false);
|
|
|
|
assert.equal(lmStudioUrl, "http://127.0.0.1:4321/v1/chat/completions");
|
|
assert.equal(vllmHeaders.Authorization, undefined);
|
|
assert.equal(vllmHeaders.Accept, "application/json");
|
|
});
|
|
|
|
test("DefaultExecutor local providers append /v1/chat/completions for bare hostname base URLs", () => {
|
|
const llamaCpp = new DefaultExecutor("llama-cpp");
|
|
const lmStudio = new DefaultExecutor("lm-studio");
|
|
const vllm = new DefaultExecutor("vllm");
|
|
|
|
const bareHost = llamaCpp.buildUrl("gemma-4", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://foo.llama.example.com" },
|
|
});
|
|
const customPath = lmStudio.buildUrl("gemma-4", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://bar.llama.ai/foo" },
|
|
});
|
|
const alreadyComplete = vllm.buildUrl("gemma-4", true, 0, {
|
|
providerSpecificData: { baseUrl: "https://baz.llama.ai/v1/chat/completions" },
|
|
});
|
|
|
|
assert.equal(bareHost, "https://foo.llama.example.com/v1/chat/completions");
|
|
assert.equal(customPath, "https://bar.llama.ai/foo/v1/chat/completions");
|
|
assert.equal(alreadyComplete, "https://baz.llama.ai/v1/chat/completions");
|
|
});
|
|
|
|
test("DefaultExecutor.buildHeaders handles Snowflake PATs and GigaChat access tokens", () => {
|
|
const snowflake = new DefaultExecutor("snowflake");
|
|
const gigachat = new DefaultExecutor("gigachat");
|
|
|
|
const snowflakePatHeaders = snowflake.buildHeaders({ apiKey: "pat/test-token" }, false);
|
|
const snowflakeJwtHeaders = snowflake.buildHeaders({ apiKey: "jwt-token" }, false);
|
|
const gigachatHeaders = gigachat.buildHeaders({ accessToken: "gigachat-token" }, false);
|
|
|
|
assert.equal(snowflakePatHeaders.Authorization, "Bearer test-token");
|
|
assert.equal(
|
|
snowflakePatHeaders["X-Snowflake-Authorization-Token-Type"],
|
|
"PROGRAMMATIC_ACCESS_TOKEN"
|
|
);
|
|
assert.equal(snowflakeJwtHeaders.Authorization, "Bearer jwt-token");
|
|
assert.equal(snowflakeJwtHeaders["X-Snowflake-Authorization-Token-Type"], "KEYPAIR_JWT");
|
|
assert.equal(gigachatHeaders.Authorization, "Bearer gigachat-token");
|
|
});
|
|
|
|
test("DefaultExecutor.buildHeaders strips DashScope headers for Qwen API keys and preserves them for OAuth", () => {
|
|
const executor = new DefaultExecutor("qwen");
|
|
|
|
const apiKeyHeaders = executor.buildHeaders({ apiKey: "dash-key" }, true);
|
|
const oauthHeaders = executor.buildHeaders({ accessToken: "oauth-token" }, true);
|
|
|
|
assert.equal(apiKeyHeaders.Authorization, "Bearer dash-key");
|
|
assert.equal(
|
|
Object.keys(apiKeyHeaders).some((key) => key.toLowerCase().startsWith("x-dashscope-")),
|
|
false
|
|
);
|
|
assert.equal(oauthHeaders.Authorization, "Bearer oauth-token");
|
|
assert.equal(oauthHeaders["X-Dashscope-AuthType"], "qwen-oauth");
|
|
assert.equal(oauthHeaders["X-Dashscope-CacheControl"], "enable");
|
|
});
|
|
|
|
test("DefaultExecutor.buildHeaders rotates extra API keys and builds Claude Code compatible headers", () => {
|
|
const openai = new DefaultExecutor("openai");
|
|
const cc = new DefaultExecutor("anthropic-compatible-cc-test");
|
|
|
|
const first = openai.buildHeaders(
|
|
{
|
|
apiKey: "primary",
|
|
connectionId: "conn-rotation",
|
|
providerSpecificData: { extraApiKeys: ["extra-1", "extra-2"] },
|
|
},
|
|
false
|
|
);
|
|
const second = openai.buildHeaders(
|
|
{
|
|
apiKey: "primary",
|
|
connectionId: "conn-rotation",
|
|
providerSpecificData: { extraApiKeys: ["extra-1", "extra-2"] },
|
|
},
|
|
false
|
|
);
|
|
const ccHeaders = cc.buildHeaders(
|
|
{
|
|
apiKey: "cc-key",
|
|
providerSpecificData: { ccSessionId: "session-1" },
|
|
},
|
|
true
|
|
);
|
|
const ccJsonHeaders = cc.buildHeaders(
|
|
{
|
|
apiKey: "cc-key",
|
|
providerSpecificData: { ccSessionId: "session-1" },
|
|
},
|
|
false
|
|
);
|
|
|
|
assert.equal(first.Authorization, "Bearer primary");
|
|
assert.equal(second.Authorization, "Bearer extra-1");
|
|
assert.equal(ccHeaders.Authorization, "Bearer cc-key");
|
|
assert.equal(ccHeaders["x-api-key"], undefined);
|
|
assert.equal(ccHeaders["anthropic-version"], CLAUDE_CODE_COMPATIBLE_ANTHROPIC_VERSION);
|
|
assert.equal(ccHeaders["X-Claude-Code-Session-Id"], "session-1");
|
|
assert.equal(ccHeaders.Accept, "application/json");
|
|
assert.equal(ccJsonHeaders.Accept, "application/json");
|
|
});
|
|
|
|
test("DefaultExecutor.execute uses CC-compatible connection defaults to append 1M beta", async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
const calls = [];
|
|
const toPlainHeaders = (headers) =>
|
|
headers instanceof Headers
|
|
? Object.fromEntries(headers.entries())
|
|
: Object.fromEntries(
|
|
Object.entries(headers || {}).map(([key, value]) => [
|
|
key,
|
|
value == null ? "" : String(value),
|
|
])
|
|
);
|
|
|
|
globalThis.fetch = async (_url, init = {}) => {
|
|
calls.push({ headers: toPlainHeaders(init.headers) });
|
|
return new Response(JSON.stringify({ ok: true }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
};
|
|
|
|
try {
|
|
const cc = new DefaultExecutor("anthropic-compatible-cc-test");
|
|
await cc.execute({
|
|
model: "claude-sonnet-4-6",
|
|
body: {
|
|
model: "claude-sonnet-4-6",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
},
|
|
stream: false,
|
|
credentials: {
|
|
apiKey: "cc-key",
|
|
providerSpecificData: {
|
|
ccSessionId: "session-1",
|
|
},
|
|
},
|
|
clientHeaders: {
|
|
"x-app": "cli",
|
|
"user-agent": "claude-cli/2.1.116 (external, cli)",
|
|
},
|
|
extendedContext: false,
|
|
});
|
|
await cc.execute({
|
|
model: "claude-sonnet-4-6",
|
|
body: {
|
|
model: "claude-sonnet-4-6",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
},
|
|
stream: false,
|
|
credentials: {
|
|
apiKey: "cc-key",
|
|
providerSpecificData: {
|
|
ccSessionId: "session-1",
|
|
requestDefaults: { context1m: true, redactThinking: true },
|
|
},
|
|
},
|
|
extendedContext: false,
|
|
});
|
|
|
|
const anthropicCompat = new DefaultExecutor("anthropic-compatible-test");
|
|
await anthropicCompat.execute({
|
|
model: "claude-sonnet-4-6",
|
|
body: {
|
|
model: "claude-sonnet-4-6",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
},
|
|
stream: false,
|
|
credentials: {
|
|
apiKey: "anth-key",
|
|
providerSpecificData: {
|
|
baseUrl: "https://anthropic.example.com/v1",
|
|
},
|
|
},
|
|
extendedContext: true,
|
|
});
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
|
|
assert.equal(calls[0].headers["anthropic-beta"].includes(CONTEXT_1M_BETA_HEADER), false);
|
|
assert.equal(
|
|
calls[0].headers["anthropic-beta"].includes(CLAUDE_CODE_COMPATIBLE_REDACT_THINKING_BETA),
|
|
false
|
|
);
|
|
assert.equal(calls[1].headers["anthropic-beta"].includes(CONTEXT_1M_BETA_HEADER), true);
|
|
assert.equal(
|
|
calls[1].headers["anthropic-beta"].includes(CLAUDE_CODE_COMPATIBLE_REDACT_THINKING_BETA),
|
|
true
|
|
);
|
|
assert.equal(calls[2].headers["anthropic-beta"], undefined);
|
|
});
|
|
|
|
test("DefaultExecutor.execute reports the exact serialized provider request before fetch", async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
let fetchStarted = false;
|
|
let fetchBody: any = null;
|
|
let prepared: any = null;
|
|
let preparedBeforeFetch = false;
|
|
|
|
globalThis.fetch = async (_url, init = {}) => {
|
|
fetchStarted = true;
|
|
fetchBody = JSON.parse(String(init.body || "{}"));
|
|
return new Response(JSON.stringify({ ok: true }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
};
|
|
|
|
try {
|
|
const cc = new DefaultExecutor("anthropic-compatible-cc-test");
|
|
const requestCapture = {
|
|
capture(request) {
|
|
preparedBeforeFetch = !fetchStarted;
|
|
prepared = request;
|
|
},
|
|
body(fallback) {
|
|
return prepared?.body ?? fallback;
|
|
},
|
|
latest() {
|
|
return prepared;
|
|
},
|
|
};
|
|
const result = await runWithCapture(requestCapture, () =>
|
|
cc.execute({
|
|
model: "claude-sonnet-4-6",
|
|
body: {
|
|
model: "claude-sonnet-4-6",
|
|
system: [
|
|
{
|
|
type: "text",
|
|
text: "x-anthropic-billing-header: cc_version=1.0.0; cc_entrypoint=sdk-cli; cch=00000;",
|
|
},
|
|
],
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
reasoning_effort: "xhigh",
|
|
},
|
|
stream: false,
|
|
credentials: {
|
|
apiKey: "cc-key",
|
|
providerSpecificData: {
|
|
ccSessionId: "session-1",
|
|
},
|
|
},
|
|
})
|
|
);
|
|
|
|
assert.ok(prepared, "prepared request hook should fire before fetch");
|
|
assert.equal(preparedBeforeFetch, true);
|
|
assert.deepEqual(prepared.body, fetchBody);
|
|
assert.deepEqual(result.transformedBody, fetchBody);
|
|
assert.equal(prepared.body.reasoning_effort, "high");
|
|
assert.equal(fetchBody.reasoning_effort, "high");
|
|
assert.match(JSON.stringify(fetchBody), /\bcch=(?!00000)[0-9a-f]{5};/);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("DefaultExecutor.execute only injects adaptive thinking defaults for Claude models that support x-high effort", async () => {
|
|
const originalFetch = globalThis.fetch;
|
|
const requestBodies = [];
|
|
|
|
globalThis.fetch = async (_url, init = {}) => {
|
|
requestBodies.push(JSON.parse(String(init.body)));
|
|
return new Response(JSON.stringify({ ok: true }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
};
|
|
|
|
try {
|
|
const claude = new DefaultExecutor("claude");
|
|
await claude.execute({
|
|
model: "claude-opus-4-7",
|
|
body: {
|
|
model: "claude-opus-4-7",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
},
|
|
stream: false,
|
|
credentials: {
|
|
apiKey: "cc-key",
|
|
providerSpecificData: {
|
|
ccSessionId: "session-1",
|
|
},
|
|
},
|
|
clientHeaders: {
|
|
"x-app": "cli",
|
|
"user-agent": "claude-cli/2.1.116 (external, cli)",
|
|
},
|
|
extendedContext: false,
|
|
});
|
|
|
|
await claude.execute({
|
|
model: "claude-haiku-4-5-20251001",
|
|
body: {
|
|
model: "claude-haiku-4-5-20251001",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
},
|
|
stream: false,
|
|
credentials: {
|
|
apiKey: "cc-key",
|
|
providerSpecificData: {
|
|
ccSessionId: "session-1",
|
|
},
|
|
},
|
|
clientHeaders: {
|
|
"x-app": "cli",
|
|
"user-agent": "claude-cli/2.1.116 (external, cli)",
|
|
},
|
|
extendedContext: false,
|
|
});
|
|
|
|
await claude.execute({
|
|
model: "claude-sonnet-4-6",
|
|
body: {
|
|
model: "claude-sonnet-4-6",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
thinking: { type: "disabled" },
|
|
},
|
|
stream: false,
|
|
credentials: {
|
|
apiKey: "cc-key",
|
|
providerSpecificData: {
|
|
ccSessionId: "session-1",
|
|
},
|
|
},
|
|
clientHeaders: {
|
|
"x-app": "cli",
|
|
"user-agent": "claude-cli/2.1.116 (external, cli)",
|
|
},
|
|
extendedContext: false,
|
|
});
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
|
|
assert.deepEqual((requestBodies[0] as any).thinking, { type: "adaptive" });
|
|
assert.deepEqual((requestBodies[0] as any).context_management, {
|
|
edits: [{ type: "clear_thinking_20251015", keep: "all" }],
|
|
});
|
|
assert.deepEqual((requestBodies[0] as any).output_config, { effort: "high" });
|
|
|
|
assert.equal((requestBodies[1] as any).thinking, undefined);
|
|
assert.equal((requestBodies[1] as any).context_management, undefined);
|
|
assert.equal((requestBodies[1] as any).output_config, undefined);
|
|
|
|
assert.deepEqual((requestBodies[2] as any).thinking, { type: "disabled" });
|
|
assert.equal((requestBodies[2] as any).context_management, undefined);
|
|
});
|
|
|
|
test("DefaultExecutor.transformRequest injects OpenAI stream usage and preserves model ids with slashes", () => {
|
|
const executor = new DefaultExecutor("openai");
|
|
const body = { model: "zai-org/GLM-5-FP8", messages: [{ role: "user", content: "hi" }] };
|
|
const result = executor.transformRequest("zai-org/GLM-5-FP8", body, true, {});
|
|
|
|
assert.notEqual(result, body);
|
|
assert.equal(result.model, "zai-org/GLM-5-FP8");
|
|
assert.deepEqual((result as any).stream_options, { include_usage: true });
|
|
assert.equal((body as any).stream_options, undefined);
|
|
});
|
|
|
|
test("DefaultExecutor.transformRequest only injects stream usage for OpenAI chat targets", () => {
|
|
const openAICompat = new DefaultExecutor("openai-compatible-test");
|
|
const openAIResponsesCompat = new DefaultExecutor("openai-compatible-responses-test");
|
|
|
|
const chatBody = { model: "gpt-4.1", messages: [{ role: "user", content: "hi" }] };
|
|
const responsesBody = { model: "gpt-4.1", input: "hi" };
|
|
|
|
const chatResult = openAICompat.transformRequest("gpt-4.1", chatBody, true, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1" },
|
|
});
|
|
const responsesResult = openAIResponsesCompat.transformRequest("gpt-4.1", responsesBody, true, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1" },
|
|
});
|
|
|
|
assert.deepEqual((chatResult as any).stream_options, { include_usage: true });
|
|
assert.equal((responsesResult as any).stream_options, undefined);
|
|
});
|
|
|
|
test("DefaultExecutor.transformRequest respects disableStreamOptions for OpenAI chat targets", () => {
|
|
const openAICompat = new DefaultExecutor("openai-compatible-test");
|
|
const chatBody = { model: "gpt-4.1", messages: [{ role: "user", content: "hi" }] };
|
|
|
|
const chatResultDisabled = openAICompat.transformRequest("gpt-4.1", chatBody, true, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1", disableStreamOptions: true },
|
|
});
|
|
|
|
const chatResultEnabled = openAICompat.transformRequest("gpt-4.1", chatBody, true, {
|
|
providerSpecificData: { baseUrl: "https://proxy.example/v1", disableStreamOptions: false },
|
|
});
|
|
|
|
assert.equal((chatResultDisabled as any).stream_options, undefined);
|
|
assert.deepEqual((chatResultEnabled as any).stream_options, { include_usage: true });
|
|
});
|
|
|
|
test("DefaultExecutor.transformRequest injects OpenRouter connection preset", () => {
|
|
const executor = new DefaultExecutor("openrouter");
|
|
const body = { model: "openai/gpt-4", messages: [{ role: "user", content: "hi" }] };
|
|
|
|
const result = executor.transformRequest("openai/gpt-4", body, true, {
|
|
providerSpecificData: { preset: " email-copywriter " },
|
|
});
|
|
|
|
assert.equal((result as any).preset, "email-copywriter");
|
|
assert.deepEqual((result as any).stream_options, { include_usage: true });
|
|
assert.equal((body as any).preset, undefined);
|
|
|
|
const explicit = executor.transformRequest(
|
|
"openai/gpt-4",
|
|
{ ...body, preset: "client-preset" },
|
|
true,
|
|
{ providerSpecificData: { preset: "connection-preset" } }
|
|
);
|
|
|
|
assert.equal((explicit as any).preset, "client-preset");
|
|
|
|
const explicitNull = executor.transformRequest("openai/gpt-4", { ...body, preset: null }, true, {
|
|
providerSpecificData: { preset: "connection-preset" },
|
|
});
|
|
assert.equal((explicitNull as any).preset, null);
|
|
|
|
const explicitEmpty = executor.transformRequest("openai/gpt-4", { ...body, preset: "" }, true, {
|
|
providerSpecificData: { preset: "connection-preset" },
|
|
});
|
|
assert.equal((explicitEmpty as any).preset, "");
|
|
|
|
const blank = executor.transformRequest("openai/gpt-4", body, true, {
|
|
providerSpecificData: { preset: " " },
|
|
});
|
|
|
|
assert.equal((blank as any).preset, undefined);
|
|
});
|
|
|
|
test("DefaultExecutor.transformRequest strips stream_options from Anthropic-compatible targets", () => {
|
|
const anthropicCompat = new DefaultExecutor("anthropic-compatible-test");
|
|
const anthropicCcCompat = new DefaultExecutor("anthropic-compatible-cc-test");
|
|
|
|
const anthropicBody = {
|
|
model: "claude-sonnet-4-6",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
stream_options: { include_usage: true },
|
|
};
|
|
const ccBody = {
|
|
model: "claude-sonnet-4-6",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
};
|
|
|
|
const anthropicResult = anthropicCompat.transformRequest(
|
|
"claude-sonnet-4-6",
|
|
anthropicBody,
|
|
true,
|
|
{}
|
|
);
|
|
const ccResult = anthropicCcCompat.transformRequest("claude-sonnet-4-6", ccBody, true, {});
|
|
|
|
assert.notEqual(anthropicResult, anthropicBody);
|
|
assert.equal((anthropicResult as any).stream_options, undefined);
|
|
assert.equal((ccResult as any).stream_options, undefined);
|
|
});
|
|
|
|
test("DefaultExecutor.transformRequest neutralizes incompatible tool_choice for Qwen thinking", () => {
|
|
const executor = new DefaultExecutor("qwen");
|
|
const body = {
|
|
messages: [{ role: "user", content: "hi" }],
|
|
thinking: { type: "enabled" },
|
|
tool_choice: { type: "function", function: { name: "pwd" } },
|
|
};
|
|
const result = executor.transformRequest("qwen3-coder-plus", body, true, {});
|
|
|
|
assert.notEqual(result, body);
|
|
assert.equal((result as any).tool_choice, "auto");
|
|
});
|
|
|
|
test("DefaultExecutor.transformRequest applies GLMT preset defaults without overriding explicit values", () => {
|
|
const executor = new DefaultExecutor("glmt");
|
|
|
|
const autoBody = {
|
|
messages: [{ role: "user", content: "hi" }],
|
|
};
|
|
const autoResult = executor.transformRequest("glm-5.1", autoBody, true, {});
|
|
|
|
assert.notEqual(autoResult, autoBody);
|
|
assert.equal((autoResult as any).max_tokens, 65536);
|
|
(assert as any).equal((autoResult as any).temperature, 0.2);
|
|
(assert as any).deepEqual((autoResult as any).thinking, {
|
|
type: "enabled",
|
|
budget_tokens: 24576,
|
|
});
|
|
|
|
const explicitBody = {
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 4096,
|
|
temperature: 0.7,
|
|
thinking: { type: "enabled" },
|
|
};
|
|
const explicitResult = executor.transformRequest("glm-5.1", explicitBody, true, {});
|
|
|
|
assert.notEqual(explicitResult, explicitBody);
|
|
assert.equal((explicitResult as any).max_tokens, 4096);
|
|
assert.equal((explicitResult as any).temperature, 0.7);
|
|
assert.deepEqual((explicitResult as any).thinking, {
|
|
type: "enabled",
|
|
budget_tokens: 4095,
|
|
});
|
|
});
|
|
|
|
test("BaseExecutor helpers manage custom user agents and upstream extra headers", () => {
|
|
const headers = { "user-agent": "old", Authorization: "Bearer old" };
|
|
|
|
assert.equal(getCustomUserAgent({ customUserAgent: " MyAgent/1.0 " }), "MyAgent/1.0");
|
|
assert.equal(getCustomUserAgent({ customUserAgent: " " }), null);
|
|
|
|
setUserAgentHeader(headers, "MyAgent/2.0");
|
|
assert.equal(headers["User-Agent"], "MyAgent/2.0");
|
|
assert.equal(headers["user-agent"], "MyAgent/2.0");
|
|
|
|
applyConfiguredUserAgent(headers, { customUserAgent: "MyAgent/3.0" });
|
|
assert.equal(headers["User-Agent"], "MyAgent/3.0");
|
|
|
|
mergeUpstreamExtraHeaders(headers, {
|
|
Authorization: "Bearer override",
|
|
"user-agent": "Merged/4.0",
|
|
"X-Upstream": "1",
|
|
});
|
|
assert.equal(headers.Authorization, "Bearer override");
|
|
assert.equal(headers["User-Agent"], "Merged/4.0");
|
|
assert.equal(headers["user-agent"], "Merged/4.0");
|
|
assert.equal(headers["X-Upstream"], "1");
|
|
});
|
|
|
|
test("BaseExecutor.mergeAbortSignals aborts when either source signal aborts", () => {
|
|
const primary = new AbortController();
|
|
const secondary = new AbortController();
|
|
const merged = mergeAbortSignals(primary.signal, secondary.signal);
|
|
|
|
assert.equal(merged.aborted, false);
|
|
const primaryReason = new Error("primary timeout");
|
|
primaryReason.name = "TimeoutError";
|
|
primary.abort(primaryReason);
|
|
assert.equal(merged.aborted, true);
|
|
assert.equal(merged.reason, primaryReason);
|
|
|
|
const otherPrimary = new AbortController();
|
|
const otherSecondary = new AbortController();
|
|
const merged2 = mergeAbortSignals(otherPrimary.signal, otherSecondary.signal);
|
|
const secondaryReason = new Error("client closed");
|
|
otherSecondary.abort(secondaryReason);
|
|
assert.equal(merged2.aborted, true);
|
|
assert.equal(merged2.reason, secondaryReason);
|
|
});
|
|
|
|
test("BaseExecutor.needsRefresh returns true only when expiry is near", () => {
|
|
const executor = new TestExecutor();
|
|
const soon = new Date(Date.now() + 60_000).toISOString();
|
|
const later = new Date(Date.now() + 60 * 60 * 1000).toISOString();
|
|
|
|
assert.equal(executor.needsRefresh({ expiresAt: soon }), true);
|
|
assert.equal(executor.needsRefresh({ expiresAt: later }), false);
|
|
assert.equal(executor.needsRefresh({}), false);
|
|
});
|
|
|
|
test("DefaultExecutor.refreshCredentials returns null without refresh token", async () => {
|
|
const executor = new DefaultExecutor("gemini");
|
|
const result = await executor.refreshCredentials({}, null);
|
|
assert.equal(result, null);
|
|
});
|
|
|
|
test("DefaultExecutor.needsRefresh requests a proactive token for GigaChat", () => {
|
|
const executor = new DefaultExecutor("gigachat");
|
|
|
|
assert.equal(executor.needsRefresh({ apiKey: "base64-basic-credentials" }), true);
|
|
assert.equal(
|
|
executor.needsRefresh({
|
|
apiKey: "base64-basic-credentials",
|
|
accessToken: "existing-token",
|
|
expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
|
}),
|
|
false
|
|
);
|
|
});
|
|
|
|
test("DefaultExecutor.refreshCredentials delegates to OAuth refresh and returns new tokens", async () => {
|
|
const executor = new DefaultExecutor("gemini");
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = async (url, options) => {
|
|
assert.match(String(url), /oauth2\.googleapis\.com/);
|
|
assert.equal(options.method, "POST");
|
|
return new Response(
|
|
JSON.stringify({
|
|
access_token: "new-access-token",
|
|
refresh_token: "new-refresh-token",
|
|
expires_in: 3600,
|
|
}),
|
|
{
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
}
|
|
);
|
|
};
|
|
|
|
try {
|
|
const result = await executor.refreshCredentials({ refreshToken: "refresh-me" }, null);
|
|
assert.deepEqual(result, {
|
|
accessToken: "new-access-token",
|
|
refreshToken: "new-refresh-token",
|
|
expiresIn: 3600,
|
|
});
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("DefaultExecutor.refreshCredentials swallows refresh errors and logs them", async () => {
|
|
const executor = new DefaultExecutor("gemini");
|
|
const originalFetch = globalThis.fetch;
|
|
const messages = [];
|
|
globalThis.fetch = async () => {
|
|
throw new Error("network down");
|
|
};
|
|
|
|
try {
|
|
const result = await executor.refreshCredentials(
|
|
{ refreshToken: "refresh-me" },
|
|
{ error: (tag, message) => messages.push({ tag, message }) }
|
|
);
|
|
assert.equal(result, null);
|
|
assert.equal(messages.length, 1);
|
|
assert.match(messages[0].message, /refresh error: network down/);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("BaseExecutor.execute returns response metadata and merges headers", async () => {
|
|
const executor = new TestExecutor();
|
|
const originalFetch = globalThis.fetch;
|
|
let captured;
|
|
globalThis.fetch = async (url, options) => {
|
|
captured = { url, options };
|
|
return new Response(JSON.stringify({ ok: true }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
};
|
|
|
|
try {
|
|
const result = await executor.execute({
|
|
model: "gpt-4.1",
|
|
body: { messages: [{ role: "user", content: "hi" }] },
|
|
stream: true,
|
|
credentials: {
|
|
apiKey: "base-key",
|
|
providerSpecificData: { customUserAgent: "CredsAgent/1.0" },
|
|
},
|
|
upstreamExtraHeaders: {
|
|
Authorization: "Bearer override",
|
|
"user-agent": "UpstreamAgent/2.0",
|
|
"X-Trace-Id": "trace-1",
|
|
},
|
|
});
|
|
|
|
assert.equal(result.url, "https://primary.example/v1/chat/completions");
|
|
assert.equal(result.response.status, 200);
|
|
(assert as any).equal((result.transformedBody as any).transformed, true);
|
|
assert.equal((result.transformedBody as any).model, "gpt-4.1");
|
|
assert.equal(result.headers.Authorization, "Bearer override");
|
|
assert.equal(result.headers["User-Agent"], "UpstreamAgent/2.0");
|
|
assert.equal(result.headers["user-agent"], undefined);
|
|
assert.equal(result.headers["X-Trace-Id"], "trace-1");
|
|
assert.equal(result.headers.Accept, "text/event-stream");
|
|
assert.equal(captured.options.body.includes('"transformed":true'), true);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("BaseExecutor.execute refreshes credentials before the request when needed", async () => {
|
|
class RefreshingExecutor extends BaseExecutor {
|
|
constructor() {
|
|
super("refreshing-provider", {
|
|
baseUrl: "https://refresh.example/v1/chat/completions",
|
|
});
|
|
}
|
|
|
|
needsRefresh() {
|
|
return true;
|
|
}
|
|
|
|
async refreshCredentials() {
|
|
return {
|
|
accessToken: "fresh-token",
|
|
expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
|
|
};
|
|
}
|
|
}
|
|
|
|
const executor = new RefreshingExecutor();
|
|
const originalFetch = globalThis.fetch;
|
|
let capturedHeaders;
|
|
globalThis.fetch = async (url, options) => {
|
|
assert.equal(String(url), "https://refresh.example/v1/chat/completions");
|
|
capturedHeaders = options.headers;
|
|
return new Response(JSON.stringify({ ok: true }), { status: 200 });
|
|
};
|
|
|
|
try {
|
|
await executor.execute({
|
|
model: "gpt-4.1",
|
|
body: {},
|
|
stream: false,
|
|
credentials: { apiKey: "stale-token" },
|
|
});
|
|
|
|
assert.equal(capturedHeaders.Authorization, "Bearer fresh-token");
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("BaseExecutor.execute falls back to the next base URL after a transport error", async () => {
|
|
const executor = new TestExecutor();
|
|
const originalFetch = globalThis.fetch;
|
|
const calls = [];
|
|
globalThis.fetch = async (url) => {
|
|
calls.push(String(url));
|
|
if (calls.length === 1) {
|
|
throw new Error("first node down");
|
|
}
|
|
return new Response("ok", { status: 200 });
|
|
};
|
|
|
|
try {
|
|
const result = await executor.execute({
|
|
model: "gpt-4.1",
|
|
body: { hello: "world" },
|
|
stream: false,
|
|
credentials: {},
|
|
});
|
|
|
|
assert.deepEqual(calls, [
|
|
"https://primary.example/v1/chat/completions",
|
|
"https://fallback.example/v1/chat/completions",
|
|
]);
|
|
assert.equal(result.url, "https://fallback.example/v1/chat/completions");
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("BaseExecutor.execute throws the last error when all URLs fail", async () => {
|
|
const executor = new TestExecutor();
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = async () => {
|
|
throw new Error("still down");
|
|
};
|
|
|
|
try {
|
|
await assert.rejects(
|
|
executor.execute({
|
|
model: "gpt-4.1",
|
|
body: {},
|
|
stream: false,
|
|
credentials: {},
|
|
}),
|
|
/still down/
|
|
);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("BaseExecutor.execute propagates aborted requests through the merged signal", async () => {
|
|
const executor = new TestExecutor({ baseUrls: ["https://single.example/v1/chat/completions"] });
|
|
const controller = new AbortController();
|
|
controller.abort();
|
|
const originalFetch = globalThis.fetch;
|
|
|
|
globalThis.fetch = async (url, options) => {
|
|
assert.equal(options.signal.aborted, true);
|
|
const error = new Error(`aborted ${url}`);
|
|
error.name = "AbortError";
|
|
throw error;
|
|
};
|
|
|
|
try {
|
|
await assert.rejects(
|
|
executor.execute({
|
|
model: "gpt-4.1",
|
|
body: {},
|
|
stream: false,
|
|
credentials: {},
|
|
signal: controller.signal,
|
|
}),
|
|
/aborted/
|
|
);
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("BaseExecutor.execute clears the startup timeout after headers arrive", async () => {
|
|
const executor = new TestExecutor({ baseUrls: ["https://single.example/v1/chat/completions"] });
|
|
const originalFetch = globalThis.fetch;
|
|
const originalFetchStartTimeoutMs = BaseExecutor.FETCH_START_TIMEOUT_MS;
|
|
let capturedSignal;
|
|
|
|
BaseExecutor.FETCH_START_TIMEOUT_MS = 20;
|
|
globalThis.fetch = async (_url, options) => {
|
|
capturedSignal = options.signal;
|
|
return new Response("ok", {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
};
|
|
|
|
try {
|
|
await executor.execute({
|
|
model: "gpt-4.1",
|
|
body: {},
|
|
stream: true,
|
|
credentials: {},
|
|
});
|
|
|
|
assert.equal(capturedSignal?.aborted, false);
|
|
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
assert.equal(capturedSignal?.aborted, false);
|
|
} finally {
|
|
BaseExecutor.FETCH_START_TIMEOUT_MS = originalFetchStartTimeoutMs;
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
// Regression test for issue #1454: duplicate anthropic-version header when
|
|
// Claude Code CLI headers are detected on the native `claude` provider.
|
|
// The provider config seeds headers with Title-Case "Anthropic-Version" while
|
|
// the Claude-Code patch injects lowercase "anthropic-version". Before the fix,
|
|
// both keys coexisted in the JS object and undici combined their values into
|
|
// "2023-06-01, 2023-06-01", causing a 400 from Anthropic.
|
|
test("DefaultExecutor.execute does not produce duplicate anthropic-version header when Claude Code CLI headers are present", async () => {
|
|
const executor = new DefaultExecutor("claude");
|
|
const originalFetch = globalThis.fetch;
|
|
let capturedHeaders: Record<string, string> = {};
|
|
|
|
globalThis.fetch = async (_url, init = {}) => {
|
|
// Capture raw headers without normalisation so case-variant duplicate keys are visible.
|
|
capturedHeaders = (init.headers as Record<string, string>) || {};
|
|
return new Response(JSON.stringify({ ok: true }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
};
|
|
|
|
try {
|
|
await executor.execute({
|
|
model: "claude-sonnet-4-6",
|
|
body: {
|
|
model: "claude-sonnet-4-6",
|
|
messages: [{ role: "user", content: "hi" }],
|
|
max_tokens: 1,
|
|
},
|
|
stream: false,
|
|
credentials: { accessToken: "oauth-token" },
|
|
clientHeaders: {
|
|
"x-app": "cli",
|
|
"user-agent": "claude-cli/2.1.116 (external, cli)",
|
|
"anthropic-beta": "oauth-2025-04-20",
|
|
},
|
|
});
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
|
|
// Must be exactly one key — not multiple case variants that undici would combine
|
|
const versionKeys = Object.keys(capturedHeaders).filter(
|
|
(k) => k.toLowerCase() === "anthropic-version"
|
|
);
|
|
assert.equal(versionKeys.length, 1, "Duplicate anthropic-version header keys found");
|
|
assert.equal(capturedHeaders[versionKeys[0]], "2023-06-01");
|
|
});
|