mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-11-30 19:26:59 +08:00
* feat(codebuddy): add CodeBuddy Code custom model management Add Tencent CodeBuddy Code (app id `codebuddy`) as an additive app. Each provider is one entry of ~/.codebuddy/models.json (the provider key is the model id; CODEBUDDY_CONFIG_DIR is honored). Other models, availableModels and unknown keys are preserved, the file is written atomically with 600 permissions, a new model is appended to a non-empty availableModels, and the default model selected in settings.json cannot be removed. models.json must stay strict JSON because CodeBuddy ignores the whole file otherwise. Global prompts are written to CODEBUDDY.md. The form offers Chat Completions and Responses protocols, token limits and capability flags, with DeepSeek, Xiaomi MiMo and LongCat presets from their CodeBuddy guides. MCP and Skills sync are not wired yet: they need enabled_codebuddy columns (a schema change), so CodeBuddy's own MCP config and skills directory are never written. Sessions, usage import and local routing are not supported. * style(codebuddy): align provider form with shared form components Build the CodeBuddy form from the same parts as the Kimi, MiniMax Code and Pi forms: ApiKeySection (get-key link, partner hint), EndpointField for the url, ModelInputWithFetch so the model id can be picked from the endpoint's /models list, Checkbox capability rows, REQUIRED_LABEL asterisks, the `grid grid-cols-2 gap-3` field pairs, numeric token inputs and the shared preset category labels. Reuse providerForm.apiEndpoint, drop the now unused CodeBuddy-specific URL and API key strings, and word the remaining copy like the other apps' (duplicate/locked ID hints, capability names, empty state). Translate the Turkish strings that were left in English. Show CodeBuddy with its own icon (from lobe-icons) instead of the Tencent logo, and label it "CodeBuddy Code" in the app config like the sidebar. * style(codebuddy): match the WorkBuddy field order and vendor label API key now comes before the request URL (as in WorkBuddy and the OpenCode-style forms), the API format and vendor fields take a full row each, and the vendor field uses the same label as WorkBuddy. * style(codebuddy): lay out the provider editor like Kimi, Pi and OpenCode The model is now a single Kimi-style row (expand arrow, model ID, display name) under a models heading with a "?" hint; token limits and capabilities (now switches) live in the expanded details. Fields follow the Kimi order (API format, API key, URL, vendor label), the API format menu shows readable protocol names, and the model-list fetch moves to the models heading with a dropdown beside the model ID. The model ID is still the card key: editable with fetch on create, locked on edit, with the duplicate and whitespace checks kept below the row. The display name column is the models.json name, i.e. the same value as the Name field. Picking a fetched model fills blank token limits and turns on image/reasoning from presets and models.dev. Labels duplicated by opencode keys are removed from all locales. * style(codebuddy): reuse the Kimi capability labels like WorkBuddy Tool use / image input / thinking now come from kimi.capabilities, so the three OpenAI-compatible model editors share one wording. The duplicate codebuddy.supports* keys are removed from all locales. * style(codebuddy): match Kimi's model row columns The display name column is optional in Kimi's header, so drop its asterisk, and keep a delete-column-wide gap at the end of the row so the model ID and display name line up with Kimi's rows. * feat(codebuddy): add enabled_codebuddy MCP and Skill flags (schema v23) Schema v22 -> v23 adds `enabled_codebuddy BOOLEAN NOT NULL DEFAULT 0` to mcp_servers and skills, in both the create statements and the migration. McpApps / SkillApps gain a `codebuddy` field mapped by the DAOs, and MCP deep links accept `codebuddy`. Projection into CodeBuddy's own files follows in the next commits. Migration tests cover a fresh database and upgrades from v22 (a minimal table and a full v22 schema), keeping existing flags and defaulting the new column to disabled. * feat(codebuddy): sync MCP servers to CodeBuddy Code's user config CodeBuddy reads exactly one user-scope MCP file: the first that exists of <config>/.mcp.json, <config>/mcp.json (deprecated) and ~/.codebuddy.json (legacy), without merging, and `codebuddy mcp add -s user` writes to the same file (verified in the 2.164 CLI and the docs). CC Switch follows the same rule, so an existing mcp.json keeps being used instead of a new .mcp.json shadowing the user's servers. CODEBUDDY_CONFIG_DIR is honored. Entries are written with an explicit type (stdio / http / sse); native fields such as defer_loading and tools, disabledMcpServers, the legacy file's projects map and the user's own servers are preserved. Writes are atomic and roll back with the database. CodeBuddy accepts JSONC, but like models.json a file with comments or trailing commas is never rewritten; import still reads it and maps disabledMcpServers to a disabled flag. The MCP panel and form get a CodeBuddy Code column. * feat(codebuddy): include CodeBuddy Code in unified Skill sync Skills are now projected into ~/.codebuddy/skills (CODEBUDDY_CONFIG_DIR aware) like any other app, replacing the previous exclusion. As with Kimi and Qwen, the directory is protected as a native one: unselected entries installed outside CC Switch are never removed, and enabling a skill over a foreign directory with the same name is refused without touching files or flags. The Skills panel and import dialog show CodeBuddy Code. * feat(codebuddy): browse CodeBuddy Code sessions and import their usage Sessions are read from <config>/projects/<sanitized cwd>/<sessionId>.jsonl. The reader shows user and assistant messages, reasoning as thinking blocks, function calls paired with their results, and per-request model/token meta; injected user messages (providerData.isMeta, e.g. task reminders) and bookkeeping events are hidden. Titles come from ai-title, else the first prompt, else the first reply (teammate sessions start from a channel message). Resume uses `codebuddy --resume <id>` with CODEBUDDY_CONFIG_DIR carried over. Deletion is refused like Kimi / Qwen / MCode: background jobs, teammates and file history refer to the transcript, and CodeBuddy has no command that removes one consistently. Usage import records one request per (messageId, stepSeq): the step's usage sits on the assistant message, or on its first function call when the step only calls tools. Main and subagents/*.jsonl transcripts are read incrementally by byte offset with permanent dedup receipts. rawUsage.prompt_tokens includes cache hits, so rows store fresh input (prompt - cache read - cache write) with cache read/write kept apart; completion_tokens already includes thinking tokens. The usage page and session filter list CodeBuddy Code. * docs(readme): mark CodeBuddy Code MCP, Skills, sessions and usage as supported * style(codebuddy): use the monochrome CodeBuddy mark The colour tile stood out next to the other app icons; the monochrome lobe-icons mark follows currentColor like most of them. * fix(codebuddy): drop the custom-local: prefix from session model ids CodeBuddy records custom models as custom-local:<id> in requestModelId, so usage rows showed the prefixed id and never matched a price. Strip any custom-*: prefix so sessions and usage use the configured model id. * refactor(codebuddy): drop the API format menu, target Chat Completions only Custom CodeBuddy models only need OpenAI Chat Completions. The endpoint hint, placeholder and model-list base now assume the full /chat/completions URL. An existing entry's api field is no longer edited by the form but is kept on save and stays visible in the JSON editor. * feat(codebuddy): collect and switch CodeBuddy Code official accounts CodeBuddy keeps one global sign-in in CodeBuddyExtension/Data/Public/auth/Tencent-Cloud.coding-copilot.info. CC Switch now keeps a private copy of each account (codebuddy_accounts.json, 0600, not synced), keyed by account.uid + auth.domain, and exposes it as the codebuddy_oauth provider of the generic auth_* commands. - Accounts are added by collecting the current sign-in, or by opening a terminal running codebuddy for /login and collecting the file once it turns into a new account or session. No OAuth of our own. - Switching takes the shared proper-lockfile style directory lock, pulls the live file back into its copy first (CodeBuddy refreshes tokens itself), writes the target via temp file + fsync + rename at 0600, drops the logged-out marker and reads the file back to verify. - Unrecognized content such as WorkBuddy's $wbEncrypted envelope is stashed byte-for-byte and never overwritten. - Removing an account only drops CC Switch's copy. * feat(codebuddy): manage CodeBuddy accounts in the Auth Center A CodeBuddy Code group in the Auth Center lists saved official accounts (nickname, China / international site, UID), collects the signed-in account, opens a terminal for /login and picks the new sign-in up automatically, and switches the active account. Running CodeBuddy sessions follow the switch on their own. * fix(codebuddy): launch the login terminal with the resolved codebuddy path A stale version-manager shim (mise reported 'codebuddy is not a valid shim') made the terminal login fail even with CodeBuddy installed. Resolve the executable through the tool search paths, preferring a real install over shims, and put its directory first on PATH so the node shebang resolves to the same install. * feat(codebuddy): query plan and credits for CodeBuddy accounts New codebuddy_account_quota command returns an account's plan name and this cycle's credits (total / remaining / used). It uses the access token in that account's saved copy, after absorbing the live sign-in file, and makes a single read-only query against the account's own site (auth.domain): POST /billing/meter/get-user-resource-summary for personal accounts, POST /v2/billing/meter/get-enterprise-user-usage for enterprise ones, with the same Authorization / X-User-Id / X-Domain / X-Product headers CodeBuddy sends. Tokens are never refreshed: an expired access or refresh token, or a 401, comes back as refresh_pending / expired instead. Only known CodeBuddy domains get a token, nothing about credentials is logged, requests time out after 10 seconds, and successful results are cached per account for 5 minutes unless forced. * feat(codebuddy): show plan and credits on Auth Center account rows Each CodeBuddy account row now carries the same quota column as Codex and Antigravity accounts: the plan name, a credits bar and the remaining (or used, per the quota display setting) credits, with the full breakdown on hover. Expired or not-yet-renewed tokens show why the quota is missing; the refresh button skips the backend cache. Strings added for zh, zh-TW, en, ja and tr. * feat(codebuddy): official sign-in cards bind an account and never enter models.json - codebuddy_config: is_official_provider / official_account_id (authBinding codebuddy_oauth) - ProviderService: add/update/save skip live writes for official cards; switch and remove-from-live reject them; delete only drops the row; validation skipped - write_live_snapshot refuses official cards as a last guard - new command codebuddy_account_switch_provider: switch CodeBuddy's sign-in to the account bound on an official card (reuses switch_to) * feat(codebuddy): switch official accounts from CodeBuddy official sign-in cards - new preset "CodeBuddy Official Sign-in" (category official): the form picks one collected account (site, plan and credits, in-use mark), can sign in through the terminal or collect the current sign-in, and binds it in meta.authBinding (codebuddy_oauth); the card name defaults to the account name - provider list: official cards get their own single-choice section with an In use status or a Switch button; a removed / expired / unbound account disables Switch with the reason; custom model cards keep Add / Remove - card shows the bound account and its credits, or asks to choose again when the account was removed - locales for zh / zh-TW / en / ja / tr * feat(codebuddy): Auth Center manages CodeBuddy accounts, switching moves to the provider list - drop the Switch item from the CodeBuddy group (ManagedAccountsGroup.onSetDefault becomes optional); keep collect, terminal sign-in, remove, nickname, credits and the CodeBuddy-in-use mark - help text points to the CodeBuddy official sign-in card; expired note no longer talks about switching; remove the unused switchTo / switched strings * feat(codebuddy): sign in to a new account while CodeBuddy is already signed in - starting a terminal sign-in collects the current login, then (under the shared directory lock) writes CodeBuddy's logout marker atomically with an ISO timestamp, so the CLI goes straight to its sign-in screen; the credential file is never touched and no server endpoint is called - cancelling the sign-in (or timing out, or starting another one) removes the marker only if it is still the one CC Switch wrote; if the lock is held the flow is kept so the restore can be retried - no lock or marker when CodeBuddy is not signed in, already signed out, or holds an unrecognized (WorkBuddy-encrypted) file - tests in temp dirs: marker written, credentials untouched, restore removes only our marker, lock blocks both write and restore * feat(codebuddy): official sign-in cards join Added / Available with one added at a time - no separate official section: the card whose account CodeBuddy is signed in to sits in Added, every other official card in Available - Add on an official card switches CodeBuddy to its account (switch_to, same rules); the previous card drops back to Available automatically - Remove on the added official card is disabled with a hint (CodeBuddy only holds one sign-in; add another official card to switch), it never signs out - removed / expired / unbound accounts keep Add disabled with the reason; official cards still never reach models.json, model cards are unchanged * feat(codebuddy): sign in to a new account from the official card form and the Auth Center - shared useCodebuddyLogin: when CodeBuddy is signed in, Sign in to new account first confirms the side effect (running sessions show as signed out until the new sign-in finishes), then starts the terminal sign-in; when not signed in it opens the terminal directly - while waiting, Restore original sign-in cancels the flow and the backend removes its logout marker; hidden once the new account is detected - the official card form selects the account the sign-in landed on (useManagedAuth gains onLoginComplete and an awaitable cancel) - Auth Center Add account / Sign in again use the same flow - locales zh / zh-TW / en / ja / tr; drop the unused Switch / Official sign-in section strings * refactor(codebuddy): drop Remove all accounts from the Auth Center group CodeBuddy accounts are removed one at a time; the group menu and the backend remove-all path are gone. * test(codebuddy): wait for the card name to follow the new sign-in * feat(codebuddy): manage the CodeBuddy Code CLI from the Apps page backend - codebuddy joins VALID_TOOLS: version probe, npm registry latest version, install (npm i -g @tencent-ai/codebuddy-code@latest) and uninstall via the npm package table - update runs `codebuddy update || <npm fallback>` on POSIX and Windows: the CLI's updater never prompts, pins npm to the running copy's prefix, handles pnpm / bun / native builds, and exits 1 when it cannot update - anchored update: npm installs chain to the sibling npm; a native build outside node_modules uses `<bin> update` alone * feat(codebuddy): CodeBuddy Code row on the Apps page - the row follows Antigravity CLI, matching the sidebar order, with install / update / uninstall and the show-in-sidebar switch - one-click install commands and the manual npm uninstall command - tests: row order, update and install of CodeBuddy Code, hiding it from the sidebar, and keeping it on when it is the last visible app * test(codebuddy): account for Oh My Pi in the Apps and session filters Oh My Pi now sits right before CodeBuddy Code on the Apps page, and the session app filter gains a 13th source. * fix(codebuddy): handle the note quota state added on main * fix(codebuddy): keep CodeBuddy adds serialized under the native provider lock #9098 moved the per-app lock out of the add path into lock_native_provider_operations, which only lists MCode, Kimi and DSH. CodeBuddy shares the user-chosen key check, so add it to the list to keep adds, edits, deletes and list refreshes serialized. * feat(i18n): add Korean and Russian CodeBuddy translations Translate the 58 CodeBuddy keys for ko and ru so locale parity holds after merging main, and move the Turkish CodeBuddy keys to their en.json positions. * fix(codebuddy): do not offer Duplicate on CodeBuddy cards A CodeBuddy card's key is the models.json model id sent upstream and is locked in the editor, so a duplicated "<id>-copy" card was written to models.json as a model the upstream does not serve and could only be deleted. Hide Duplicate on CodeBuddy model and official sign-in cards and guard handleDuplicateProvider for any other caller. * fix(codebuddy): reset fetched models when the API type or preset changes The fetched model list was already dropped and in-flight requests invalidated when the URL or API key changed; also key the reset on the api field and the selected preset, and cover the reset and the stale response with tests. * fix(codebuddy): re-sign-in, usage query, sub-agent usage, MCP enable and stale logout marker - Auth Center re-sign-in on a CodeBuddy account runs a normal terminal sign-in instead of being rejected as targeted re-authentication; capture replaces the old copy by uid + site. - Usage query on model cards reads the entry's url / apiKey, dropping the trailing /chat/completions on both the frontend and the backend resolver. - Sub-agent transcripts are attributed to the parent session, so the session reader header includes their tokens and cost. - Enabling an MCP server in CC Switch also drops its id from the native disabledMcpServers list, so CodeBuddy actually loads it. - The logout marker written for a terminal sign-in is recorded on disk; on startup a marker that is still ours is removed, restoring the previous sign-in after CC Switch quit mid-login. * docs(readme): list CodeBuddy Code in zh-TW, ko, tr and ru; drop unrelated test formatting * test(msw): answer codebuddy_account_live in the shared handlers Since #9578 a request without a handler fails the test. Auth Center's CodeBuddy section reads the local login as soon as it opens, which the Kimi and DeepSeek dialog tests now hit. * chore(codebuddy): follow upstream app caps and knip rules Declare the new plugins capability as false for CodeBuddy, and drop the default exports of CodebuddyAccountSection and CodebuddyOfficialAccountField: both are imported by name and knip flags the default as a duplicate. * fix(codebuddy): skip unreadable stored rows when importing native MCP servers Since #9767 get_all_mcp_servers() fails on any unreadable row, so one corrupt or newer-version server would make the CodeBuddy import (and the import from all apps) fail. Read the rows like the other importers and skip an unreadable id instead of re-creating it. Also cover the CodeBuddy id aliases in the stream check app id test. * fix(codebuddy): official preset subtitle, managed account usage tracking, and refresh-all quota --------- Co-authored-by: allenxu09 <s23372.xu@stu.scie.com.cn> Co-authored-by: funkpopo <funkpopoisme@gmail.com> Co-authored-by: Jason <farion1231@gmail.com>
433 lines
12 KiB
TypeScript
433 lines
12 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
||
|
||
import {
|
||
fillCodebuddyModel,
|
||
fillCodexCatalogModel,
|
||
fillHermesModel,
|
||
fillKimiModel,
|
||
fillOpenClawModel,
|
||
fillOpenCodeModel,
|
||
fillWorkBuddyModel,
|
||
piPresetThinkingFor,
|
||
piSendsReasoningEffort,
|
||
piThinkingLevelMapFromEfforts,
|
||
} from "@/components/providers/forms/modelMetadataFill";
|
||
import type { KnownModelMetadata } from "@/lib/modelMetadata";
|
||
|
||
const metadata: KnownModelMetadata = {
|
||
contextWindow: 262144,
|
||
maxOutputTokens: 32768,
|
||
reasoning: true,
|
||
reasoningEfforts: ["max", "low", "turbo", "high"],
|
||
inputModalities: ["text", "image", "video"],
|
||
outputModalities: ["text"],
|
||
cost: { input: 1, output: 4 },
|
||
};
|
||
|
||
const CODEX_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"];
|
||
|
||
describe("fillCodexCatalogModel", () => {
|
||
it("fills blank fields in Codex's level order", () => {
|
||
expect(
|
||
fillCodexCatalogModel(
|
||
{ model: "kimi-k2.6", contextWindow: "" },
|
||
metadata,
|
||
CODEX_LEVELS,
|
||
),
|
||
).toEqual({
|
||
model: "kimi-k2.6",
|
||
contextWindow: "262144",
|
||
reasoningLevels: ["low", "high", "max"],
|
||
inputModalities: ["text", "image"],
|
||
});
|
||
});
|
||
|
||
it("never overwrites what the user already set", () => {
|
||
const row = {
|
||
model: "kimi-k2.6",
|
||
contextWindow: "128000",
|
||
reasoningLevels: ["high"],
|
||
inputModalities: ["text"],
|
||
};
|
||
expect(fillCodexCatalogModel(row, metadata, CODEX_LEVELS)).toEqual(row);
|
||
});
|
||
|
||
it("never turns image input off for a text-only lookup", () => {
|
||
expect(
|
||
fillCodexCatalogModel(
|
||
{ model: "deepseek-v4.1-flash-1017", contextWindow: "" },
|
||
{ contextWindow: 1_000_000, inputModalities: ["text"] },
|
||
CODEX_LEVELS,
|
||
),
|
||
).toEqual({
|
||
model: "deepseek-v4.1-flash-1017",
|
||
contextWindow: "1000000",
|
||
});
|
||
});
|
||
});
|
||
|
||
describe("fillOpenClawModel", () => {
|
||
it("fills numbers and cost, and upgrades the default text-only input", () => {
|
||
expect(
|
||
fillOpenClawModel({ id: "m", name: "m", input: ["text"] }, metadata),
|
||
).toEqual({
|
||
id: "m",
|
||
name: "m",
|
||
contextWindow: 262144,
|
||
maxTokens: 32768,
|
||
reasoning: true,
|
||
input: ["text", "image"],
|
||
cost: { input: 1, output: 4 },
|
||
});
|
||
});
|
||
|
||
it("keeps user values and never downgrades capabilities", () => {
|
||
const model = {
|
||
id: "m",
|
||
name: "m",
|
||
contextWindow: 1000,
|
||
maxTokens: 10,
|
||
reasoning: true,
|
||
input: ["text", "image"],
|
||
cost: { input: 9, output: 9 },
|
||
};
|
||
expect(
|
||
fillOpenClawModel(model, {
|
||
...metadata,
|
||
reasoning: false,
|
||
inputModalities: ["text"],
|
||
}),
|
||
).toEqual(model);
|
||
});
|
||
});
|
||
|
||
describe("fillHermesModel", () => {
|
||
it("fills context_length and supports_vision only when blank", () => {
|
||
expect(fillHermesModel({ id: "m" }, metadata)).toEqual({
|
||
id: "m",
|
||
context_length: 262144,
|
||
supports_vision: true,
|
||
});
|
||
expect(
|
||
fillHermesModel(
|
||
{ id: "m", context_length: 1, supports_vision: true },
|
||
metadata,
|
||
),
|
||
).toEqual({ id: "m", context_length: 1, supports_vision: true });
|
||
});
|
||
|
||
it("only fills supports_vision towards true and keeps an explicit false", () => {
|
||
expect(fillHermesModel({ id: "m" }, { inputModalities: ["text"] })).toEqual(
|
||
{ id: "m" },
|
||
);
|
||
expect(
|
||
fillHermesModel({ id: "m", supports_vision: false }, metadata),
|
||
).toEqual({ id: "m", context_length: 262144, supports_vision: false });
|
||
});
|
||
});
|
||
|
||
describe("fillOpenCodeModel", () => {
|
||
it("fills missing limits, modalities and reasoning", () => {
|
||
expect(fillOpenCodeModel({ name: "m" }, metadata)).toEqual({
|
||
name: "m",
|
||
limit: { context: 262144, output: 32768 },
|
||
reasoning: true,
|
||
modalities: { input: ["text", "image", "video"], output: ["text"] },
|
||
});
|
||
});
|
||
|
||
it("only fills reasoning towards true and keeps an explicit value", () => {
|
||
expect(fillOpenCodeModel({ name: "m" }, { reasoning: false })).toEqual({
|
||
name: "m",
|
||
});
|
||
expect(
|
||
fillOpenCodeModel({ name: "m", reasoning: false }, { reasoning: true }),
|
||
).toEqual({ name: "m", reasoning: false });
|
||
});
|
||
|
||
it("only fills the missing half of limit", () => {
|
||
expect(
|
||
fillOpenCodeModel(
|
||
{
|
||
name: "m",
|
||
limit: { context: 1000 },
|
||
modalities: { input: ["text"] },
|
||
},
|
||
metadata,
|
||
),
|
||
).toEqual({
|
||
name: "m",
|
||
limit: { context: 1000, output: 32768 },
|
||
modalities: { input: ["text"] },
|
||
reasoning: true,
|
||
});
|
||
});
|
||
|
||
it("leaves the model untouched when nothing is known", () => {
|
||
expect(fillOpenCodeModel({ name: "m" }, {})).toEqual({ name: "m" });
|
||
});
|
||
});
|
||
|
||
describe("fillKimiModel", () => {
|
||
it("replaces a placeholder window and adds supported capabilities", () => {
|
||
expect(
|
||
fillKimiModel(
|
||
{ model: "m", max_context_size: 1, capabilities: ["tool_use"] },
|
||
metadata,
|
||
{ replaceContext: true },
|
||
),
|
||
).toEqual({
|
||
model: "m",
|
||
max_context_size: 262144,
|
||
capabilities: ["tool_use", "image_in", "thinking"],
|
||
});
|
||
});
|
||
|
||
it("keeps a window the user set and never removes capabilities", () => {
|
||
const model = {
|
||
model: "m",
|
||
max_context_size: 1000,
|
||
capabilities: ["thinking", "video_in"],
|
||
};
|
||
expect(
|
||
fillKimiModel(
|
||
model,
|
||
{ contextWindow: 9, inputModalities: ["text"], reasoning: false },
|
||
{ replaceContext: false },
|
||
),
|
||
).toEqual(model);
|
||
});
|
||
});
|
||
|
||
describe("piThinkingLevelMapFromEfforts", () => {
|
||
it("follows Pi's own models.dev rule", () => {
|
||
expect(piThinkingLevelMapFromEfforts(["high", "max"])).toEqual({
|
||
off: null,
|
||
minimal: null,
|
||
low: null,
|
||
medium: null,
|
||
high: "high",
|
||
xhigh: null,
|
||
max: "max",
|
||
});
|
||
expect(piThinkingLevelMapFromEfforts(["none", "low"])).toMatchObject({
|
||
off: "none",
|
||
low: "low",
|
||
high: null,
|
||
});
|
||
});
|
||
|
||
it("generates nothing without a Pi level", () => {
|
||
expect(piThinkingLevelMapFromEfforts(undefined)).toBeUndefined();
|
||
expect(piThinkingLevelMapFromEfforts(["default"])).toBeUndefined();
|
||
});
|
||
});
|
||
|
||
describe("piSendsReasoningEffort", () => {
|
||
const base = {
|
||
api: "openai-completions",
|
||
baseUrl: "https://relay.example.com/v1",
|
||
providerId: "relay",
|
||
compat: {},
|
||
};
|
||
|
||
it("accepts Responses and plain Chat Completions endpoints", () => {
|
||
expect(piSendsReasoningEffort({ ...base, api: "openai-responses" })).toBe(
|
||
true,
|
||
);
|
||
expect(piSendsReasoningEffort(base)).toBe(true);
|
||
});
|
||
|
||
it("accepts Pi's native Mistral protocol", () => {
|
||
expect(
|
||
piSendsReasoningEffort({
|
||
...base,
|
||
api: "mistral-conversations",
|
||
baseUrl: "https://api.mistral.ai",
|
||
}),
|
||
).toBe(true);
|
||
});
|
||
|
||
it("rejects protocols and endpoints with their own thinking format", () => {
|
||
expect(piSendsReasoningEffort({ ...base, api: "anthropic-messages" })).toBe(
|
||
false,
|
||
);
|
||
for (const baseUrl of [
|
||
"https://api.deepseek.com",
|
||
"https://open.bigmodel.cn/api/paas/v4",
|
||
"https://openrouter.ai/api/v1",
|
||
"https://api.moonshot.cn/v1",
|
||
]) {
|
||
expect(piSendsReasoningEffort({ ...base, baseUrl })).toBe(false);
|
||
}
|
||
expect(piSendsReasoningEffort({ ...base, providerId: "zai" })).toBe(false);
|
||
});
|
||
|
||
it("lets explicit compat override the detection", () => {
|
||
expect(
|
||
piSendsReasoningEffort({
|
||
...base,
|
||
baseUrl: "https://api.deepseek.com",
|
||
compat: { thinkingFormat: "openai" },
|
||
}),
|
||
).toBe(true);
|
||
expect(
|
||
piSendsReasoningEffort({
|
||
...base,
|
||
compat: { supportsReasoningEffort: false },
|
||
}),
|
||
).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("piPresetThinkingFor", () => {
|
||
const piThinking = {
|
||
thinkingLevelMap: { low: "low", high: "high" },
|
||
api: "openai-completions",
|
||
baseUrl: "https://api.moonshot.cn/v1",
|
||
compat: { supportsReasoningEffort: true, thinkingFormat: "openai" },
|
||
};
|
||
const effective = {
|
||
api: "openai-completions",
|
||
baseUrl: "https://api.moonshot.cn/v1",
|
||
providerId: "my-moonshot",
|
||
compat: {},
|
||
};
|
||
|
||
it("returns the map with the compat it still needs", () => {
|
||
expect(
|
||
piPresetThinkingFor(piThinking, {
|
||
...effective,
|
||
compat: { thinkingFormat: "openai" },
|
||
}),
|
||
).toEqual({
|
||
map: { low: "low", high: "high" },
|
||
missingCompat: { supportsReasoningEffort: true },
|
||
});
|
||
});
|
||
|
||
it("skips the map under another protocol or conflicting compat", () => {
|
||
expect(
|
||
piPresetThinkingFor(piThinking, {
|
||
...effective,
|
||
api: "anthropic-messages",
|
||
}),
|
||
).toBeNull();
|
||
expect(
|
||
piPresetThinkingFor(piThinking, {
|
||
...effective,
|
||
compat: { supportsReasoningEffort: false },
|
||
}),
|
||
).toBeNull();
|
||
expect(piPresetThinkingFor(undefined, effective)).toBeNull();
|
||
});
|
||
|
||
it("checks the behavior a preset relies on through Pi's own detection", () => {
|
||
// OpenCode Go 的预设没写 compat,靠 Pi 按地址探测出会发 reasoning_effort。
|
||
const relying = {
|
||
thinkingLevelMap: { high: "high", max: "max" },
|
||
api: "openai-completions",
|
||
baseUrl: "https://opencode.ai/zen/go/v1",
|
||
};
|
||
const goEndpoint = {
|
||
...effective,
|
||
baseUrl: "https://opencode.ai/zen/go/v1",
|
||
};
|
||
expect(piPresetThinkingFor(relying, goEndpoint)?.map).toEqual({
|
||
high: "high",
|
||
max: "max",
|
||
});
|
||
expect(
|
||
piPresetThinkingFor(relying, {
|
||
...goEndpoint,
|
||
compat: { supportsReasoningEffort: false },
|
||
}),
|
||
).toBeNull();
|
||
});
|
||
|
||
it("fills blank CodeBuddy token limits and only turns capabilities on", () => {
|
||
expect(
|
||
fillCodebuddyModel(
|
||
{ url: "https://e.example", maxOutputTokens: 4096 },
|
||
metadata,
|
||
),
|
||
).toEqual({
|
||
url: "https://e.example",
|
||
maxInputTokens: 262144,
|
||
maxOutputTokens: 4096,
|
||
supportsImages: true,
|
||
supportsReasoning: true,
|
||
});
|
||
expect(
|
||
fillCodebuddyModel(
|
||
{ supportsImages: true, supportsReasoning: true },
|
||
{ reasoning: false, inputModalities: ["text"] },
|
||
),
|
||
).toEqual({ supportsImages: true, supportsReasoning: true });
|
||
});
|
||
});
|
||
|
||
describe("fillWorkBuddyModel", () => {
|
||
const url = "https://api.example.test/v1";
|
||
const efforts = {
|
||
reasoning: {
|
||
supportedEfforts: ["low", "high", "max"],
|
||
defaultEffort: "high",
|
||
canDisableThinking: false,
|
||
},
|
||
thinkingLevelMap: {
|
||
off: null,
|
||
minimal: null,
|
||
low: "low",
|
||
medium: null,
|
||
high: "high",
|
||
xhigh: null,
|
||
max: "max",
|
||
},
|
||
};
|
||
|
||
it("fills blank limits and only turns capabilities on", () => {
|
||
expect(
|
||
fillWorkBuddyModel(
|
||
{ id: "m", supportsToolCall: true, supportsImages: false },
|
||
metadata,
|
||
url,
|
||
),
|
||
).toEqual({
|
||
id: "m",
|
||
supportsToolCall: true,
|
||
supportsImages: true,
|
||
supportsReasoning: true,
|
||
maxInputTokens: 262144,
|
||
maxOutputTokens: 32768,
|
||
...efforts,
|
||
});
|
||
expect(
|
||
fillWorkBuddyModel(
|
||
{ id: "m", maxInputTokens: 1000, supportsReasoning: true },
|
||
{ reasoning: false, contextWindow: 2000 },
|
||
url,
|
||
),
|
||
).toEqual({ id: "m", maxInputTokens: 1000, supportsReasoning: true });
|
||
});
|
||
|
||
it("derives effort levels only where they reach the upstream", () => {
|
||
// Moonshot 不认 reasoning_effort(Pi 的探测规则),不列强度
|
||
expect(
|
||
fillWorkBuddyModel({ id: "m" }, metadata, "https://api.moonshot.cn/v1"),
|
||
).not.toHaveProperty("reasoning");
|
||
// 已有的强度或映射不动
|
||
const kept = {
|
||
id: "m",
|
||
supportsReasoning: true,
|
||
thinkingLevelMap: { max: "max" },
|
||
};
|
||
expect(fillWorkBuddyModel(kept, metadata, url)).toEqual({
|
||
...kept,
|
||
supportsImages: true,
|
||
maxInputTokens: 262144,
|
||
maxOutputTokens: 32768,
|
||
});
|
||
});
|
||
});
|