diff --git a/README.md b/README.md index 6c3b306..03cd02b 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ A [pi](https://shittycodingagent.ai/) provider extension that connects pi to the - **Two provider entries**: - `qoder` — Global / international Qoder. - - `qoder-cn` — Qoder China, forced to CN endpoints and independent of `QODER_REGION`. + - `qoder-cn` — Qoder China, always bound to CN endpoints. - **Interactive Login**: Global Qoder supports browser device-code flow or Personal Access Token (PAT) login. - **Qoder CN PAT Login**: China edition uses a separate PAT login entry (`/login qoder-cn`) and CN token exchange endpoints. - **WAF Bypass**: Built-in WAF obfuscation and body encoding (`Encode=1`). @@ -64,18 +64,6 @@ Qoder China: > The exchanged job token is short-lived; the provider transparently re-exchanges > the stored PAT when it expires. -### Region environment variables - -The provider also understands these optional variables: - -```bash -export QODER_REGION=cn # or QODER_BACKEND=cn / QODER_MODE=cn -``` - -Setting a CN PAT without a global PAT also auto-selects CN mode for the `qoder` -entry, but the recommended explicit China entry is still `/login qoder-cn` and -`--provider qoder-cn`. - ## Endpoints Global: @@ -112,9 +100,9 @@ removed), including: - `Kimi-K3` - `MiniMax-M3` -The original service keys remain compatibility aliases, so existing commands -such as `--model lite` and references such as `qoder/lite` still send the -upstream `lite` key. +Only these friendly IDs are public. Service keys such as `lite`, `qfmodel`, and +`qmodel` cannot be selected with `--model`; the provider maps the chosen +friendly ID to its internal service key only when sending a request. Global models default to a 1M context window, matching the Qoder API (verified against `lite` with prompts up to 1,000K tokens). `kmodel` stays at the 256K its @@ -128,31 +116,28 @@ internal keys at request time: | Friendly ID | Qoder CN key | Context | Images | Reasoning | | --- | --- | ---: | :---: | :---: | -| `auto` | `auto` | 200K | ✅ | ✅ | -| `qwen3.7-max` | `qmodel_latest` | 1M | ✅ | ✅ | -| `qwen3.7-plus` | `qmodel` | 1M | ❌ | ✅ | -| `qwen3.6-flash` | `q36fmodel` | 1M | ❌ | ✅ | -| `deepseek-v4-pro` | `dmodel` | 1M | ❌ | ✅ | -| `deepseek-v4-flash` | `dfmodel` | 1M | ❌ | ❌ | -| `glm-5.2` | `gm51model` | 200K | ✅ | ✅ | -| `kimi-k2.6` | `kmodel` | 256K | ✅ | ✅ | -| `minimax-m2.7` | `mmodel` | 200K | ❌ | ❌ | - -Compatibility aliases are also accepted for request mapping, such as -`qwen3.6-plus` → `qmodel`, `glm-5.1` → `gm51model`, and `minimax-m3` → `mmodel`. +| `Auto` | `auto` | 200K | ✅ | ✅ | +| `Qwen3.7-Max` | `qmodel_latest` | 1M | ✅ | ✅ | +| `Qwen3.7-Plus` | `qmodel` | 1M | ❌ | ✅ | +| `Qwen3.6-Flash` | `q36fmodel` | 1M | ❌ | ✅ | +| `DeepSeek-V4-Pro` | `dmodel` | 1M | ❌ | ✅ | +| `DeepSeek-V4-Flash` | `dfmodel` | 1M | ❌ | ❌ | +| `GLM-5.2` | `gm51model` | 200K | ✅ | ✅ | +| `Kimi-K2.7-Code` | `kmodel` | 256K | ✅ | ✅ | +| `MiniMax-M2.7` | `mmodel` | 200K | ❌ | ❌ | ## Usage Once logged in, select any Qoder model in pi: ```text -/model qwen3.7-plus +/model Qwen3.7-Plus ``` Or start directly: ```bash -pi --provider qoder-cn --model qwen3.7-plus +pi --provider qoder-cn --model Qwen3.7-Plus ``` Global example: @@ -165,16 +150,20 @@ pi --provider qoder --model Lite ```text src/ -├── index.ts # Extension registration -├── cosy.ts # COSY signature, machine ID, region/endpoints, friendly model IDs -├── login.ts # OAuth device flow + PAT login sequence -├── pat.ts # PAT → job-token exchange + identity resolution -├── models.ts # Model definitions and dynamic config cache -├── oauth.ts # PAT / OAuth callback orchestrator -├── stream.ts # Main streaming response handler -├── transform.ts # Message conversions (OpenAI schema mapping) -├── thinking-parser.ts # Fallback tag parser -└── qoder-encoding.ts # WAF bypass body encoder +├── index.ts # Register the two providers +├── region.ts # Fixed global/CN configuration and URL helpers +├── cosy.ts # COSY signing, machine ID, and gateway headers +├── catalog.ts # Friendly model IDs, live catalog cache, static seeds +├── auth/ +│ ├── pat.ts # PAT → job-token exchange and identity +│ ├── login.ts # Browser/PAT login sequence +│ ├── oauth.ts # OAuth callback and credential orchestration +│ └── usage.ts # Quota reporting +└── protocol/ + ├── stream.ts # Shared streaming request/response handler + ├── transform.ts # Message and tool conversion + ├── encoding.ts # WAF bypass body encoder + └── thinking.ts # Fallback tag parser ``` ## License diff --git a/scripts/live-bug-test.ts b/scripts/live-bug-test.ts index e09410a..0492489 100644 --- a/scripts/live-bug-test.ts +++ b/scripts/live-bug-test.ts @@ -17,12 +17,16 @@ import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; -import { buildAuthHeaders, getQoderChatURL, getQoderMode } from "../src/cosy.js"; -import { qoderEncodeBody } from "../src/qoder-encoding.js"; -import { transformMessagesForQoder, transformTools } from "../src/transform.js"; +import { getCachedModelConfig } from "../src/catalog.js"; +import { buildAuthHeaders } from "../src/cosy.js"; +import { qoderEncodeBody } from "../src/protocol/encoding.js"; +import { transformMessagesForQoder, transformTools } from "../src/protocol/transform.js"; +import { getQoderChatURL } from "../src/region.js"; const AUTH_FILE = join(homedir(), ".pi", "agent", "auth.json"); -const MODEL = process.argv[2] || "lite"; +const MODEL_ID = process.argv[2] || "Lite"; +const MODEL = getCachedModelConfig(MODEL_ID, "global")?.key; +if (!MODEL) throw new Error(`Unknown friendly Qoder model id: ${MODEL_ID}`); interface QoderCreds { access: string; @@ -89,8 +93,7 @@ interface TestResult { /** Send a request, decode the SSE envelope stream, return a verdict. */ async function sendRequest(label: string, body: Record): Promise { - const mode = getQoderMode(); - const url = getQoderChatURL(mode); + const url = getQoderChatURL("global"); const creds = loadCreds(); // CRITICAL: body must be encoded with qoderEncodeBody, and auth headers @@ -172,7 +175,7 @@ function fmt(r: TestResult) { async function main() { const creds = loadCreds(); - console.log(`Loaded credentials: userID=${creds.userID} email=${creds.email} mode=${getQoderMode()}`); + console.log(`Loaded credentials: userID=${creds.userID} email=${creds.email} mode=global`); const piTools = [ { diff --git a/scripts/live-thinking-leak-test.ts b/scripts/live-thinking-leak-test.ts index 9911995..3c34a66 100644 --- a/scripts/live-thinking-leak-test.ts +++ b/scripts/live-thinking-leak-test.ts @@ -10,24 +10,28 @@ * 3. For comparison, that the OLD parser logic leaks `` into text * on the same stream. * - * Usage: npx tsx scripts/live-thinking-leak-test.ts [model] [prompt] - * model defaults to "efficient" (the model that leaked historically) + * Usage: npx tsx scripts/live-thinking-leak-test.ts [friendly-model-id] [prompt] + * model defaults to "Efficient" (the model that leaked historically) */ import { readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream } from "@earendil-works/pi-ai"; -import { buildAuthHeaders, getQoderChatURL, getQoderMode } from "../src/cosy.js"; -import { qoderEncodeBody } from "../src/qoder-encoding.js"; -import { transformMessagesForQoder } from "../src/transform.js"; +import { getCachedModelConfig } from "../src/catalog.js"; +import { buildAuthHeaders } from "../src/cosy.js"; +import { qoderEncodeBody } from "../src/protocol/encoding.js"; +import { transformMessagesForQoder } from "../src/protocol/transform.js"; import { THINKING_TAG_VARIANTS, ThinkingTagParser, stripThinkingTags, -} from "../src/thinking-parser.js"; +} from "../src/protocol/thinking.js"; +import { getQoderChatURL } from "../src/region.js"; const AUTH_FILE = join(homedir(), ".pi", "agent", "auth.json"); -const MODEL = process.argv[2] || "efficient"; +const MODEL_ID = process.argv[2] || "Efficient"; +const MODEL = getCachedModelConfig(MODEL_ID, "global")?.key; +if (!MODEL) throw new Error(`Unknown friendly Qoder model id: ${MODEL_ID}`); const PROMPT = process.argv[3] || "A bat and a ball cost $1.10 in total. The bat costs $1.00 more than the ball. How much does the ball cost? Reason carefully step by step before answering."; @@ -95,8 +99,7 @@ interface RawStream { /** POST and collect every raw delta.reasoning_content / delta.content chunk. */ async function captureRawStream(model: string, isReasoning: boolean): Promise { - const mode = getQoderMode(); - const url = getQoderChatURL(mode); + const url = getQoderChatURL("global"); const creds = loadCreds(); const messages = transformMessagesForQoder([{ role: "user", content: PROMPT } as never]); const body = buildRequestBody(model, messages, isReasoning); diff --git a/scripts/record-live-fixtures.ts b/scripts/record-live-fixtures.ts index 604124f..475c444 100644 --- a/scripts/record-live-fixtures.ts +++ b/scripts/record-live-fixtures.ts @@ -136,9 +136,9 @@ async function recordRegion(region: Region, pat: string): Promise { return response; }) as typeof fetch; - const { credentialsFromPat } = await import("../src/pat.js"); - const { getCachedModelConfig, getCachedModels, updateQoderModelsCache } = await import("../src/models.js"); - const { streamQoder } = await import("../src/stream.js"); + const { credentialsFromPat } = await import("../src/auth/pat.js"); + const { getCachedModelConfig, getCachedModels, updateQoderModelsCache } = await import("../src/catalog.js"); + const { streamQoder } = await import("../src/protocol/stream.js"); const credentials = (await credentialsFromPat(pat, region)) as unknown as { access: string; diff --git a/src/__tests__/models-cache.test.ts b/src/__tests__/catalog-cache.test.ts similarity index 81% rename from src/__tests__/models-cache.test.ts rename to src/__tests__/catalog-cache.test.ts index aa1be49..674954d 100644 --- a/src/__tests__/models-cache.test.ts +++ b/src/__tests__/catalog-cache.test.ts @@ -2,7 +2,7 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { getCachedModels, updateQoderModelsCache } from "../models.js"; +import { getCachedModelConfig, getCachedModels, updateQoderModelsCache } from "../catalog.js"; import { loadLiveFixture, responseFromFixture } from "./live-fixture.js"; const CACHE_PATHS = { @@ -44,11 +44,37 @@ describe("Qoder model cache", () => { const catalog = interaction.response.body as { chat: Array<{ key: string; display_name: string }> }; for (const entry of catalog.chat) { const friendlyId = entry.display_name.replace(/\s+/g, ""); - expect(cache.configs[entry.key]?.key).toBe(entry.key); expect(cache.configs[friendlyId]?.key).toBe(entry.key); + expect(cache.configs[entry.key]).toBeUndefined(); + expect(getCachedModelConfig(friendlyId, region)?.key).toBe(entry.key); + expect(getCachedModelConfig(entry.key, region)).toBeNull(); } }); + it("does not register raw live-catalog keys as public model ids", async () => { + vi.stubGlobal( + "fetch", + vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + chat: [ + { key: "lite", enable: true, display_name: "Lite" }, + { key: "qfmodel", enable: true, display_name: "Qwen3.8-Flash" }, + ], + }), + }), + ); + + await updateQoderModelsCache("access-token", "user-id", "Test User", "test@example.com", "global"); + + expect(getCachedModels("global").map((model) => model.id)).toEqual(["Lite", "Qwen3.8-Flash"]); + expect(getCachedModelConfig("Lite", "global")?.key).toBe("lite"); + expect(getCachedModelConfig("Qwen3.8-Flash", "global")?.key).toBe("qfmodel"); + expect(getCachedModelConfig("lite", "global")).toBeNull(); + expect(getCachedModelConfig("qfmodel", "global")).toBeNull(); + }); + it("keeps only enabled service models without adding auto as a fallback", async () => { vi.stubGlobal( "fetch", @@ -99,7 +125,7 @@ describe("Qoder model cache", () => { "utf8", ); - expect(getCachedModels("global").map((model) => model.id)).toEqual(["ultimate"]); + expect(getCachedModels("global").map((model) => model.id)).toEqual(["Ultimate"]); }); it("records a 1M context window when the catalog omits context_config", async () => { diff --git a/src/__tests__/models.test.ts b/src/__tests__/catalog.test.ts similarity index 83% rename from src/__tests__/models.test.ts rename to src/__tests__/catalog.test.ts index 112932b..4236f1a 100644 --- a/src/__tests__/models.test.ts +++ b/src/__tests__/catalog.test.ts @@ -5,8 +5,9 @@ import { getCachedModelConfig, staticCnModels, staticModels, + toQoderModelId, ZERO_COST, -} from "../models.js"; +} from "../catalog.js"; // ── staticModels ────────────────────────────────────────────────────────── @@ -56,10 +57,11 @@ describe("staticModels", () => { expect(staticModels.find((m) => m.upstreamKey === "kmodel")?.contextWindow).toBe(256000); }); - it("maps friendly ids and legacy keys to the same static upstream key", () => { + it("maps friendly ids to static upstream keys without raw-key aliases", () => { expect(getCachedModelConfig("Lite", "global")?.key).toBe("lite"); - expect(getCachedModelConfig("lite", "global")?.key).toBe("lite"); expect(getCachedModelConfig("Qwen3.8-Max", "global")?.key).toBe("qmodel_preview"); + expect(getCachedModelConfig("lite", "global")).toBeNull(); + expect(getCachedModelConfig("qmodel_preview", "global")).toBeNull(); }); }); @@ -96,6 +98,13 @@ describe("staticCnModels", () => { expect(new Set(ids).size).toBe(ids.length); }); + it("uses friendly IDs only in both static region catalogs", () => { + for (const model of [...staticModels, ...staticCnModels]) { + expect(model.id).toBe(toQoderModelId(model.name)); + expect(model.id).not.toBe(model.upstreamKey); + } + }); + it("every CN model has a description", () => { for (const m of staticCnModels) { expect(m.description).toBeTruthy(); @@ -135,6 +144,19 @@ describe("contextWindowFromCatalog", () => { }); }); +describe("toQoderModelId", () => { + it("strips whitespace from catalog display names", () => { + expect(toQoderModelId("Qwen3.8-Flash")).toBe("Qwen3.8-Flash"); + expect(toQoderModelId("Qwen 3.8 Max")).toBe("Qwen3.8Max"); + expect(toQoderModelId("DeepSeek V4 Pro")).toBe("DeepSeekV4Pro"); + }); + + it("uses a stable fallback when the display name is absent", () => { + expect(toQoderModelId()).toBe("QoderModel"); + expect(toQoderModelId("")).toBe("QoderModel"); + }); +}); + // ── ZERO_COST ───────────────────────────────────────────────────────────── describe("ZERO_COST", () => { diff --git a/src/__tests__/cosy.test.ts b/src/__tests__/cosy.test.ts index 9ed3765..4b00f23 100644 --- a/src/__tests__/cosy.test.ts +++ b/src/__tests__/cosy.test.ts @@ -1,184 +1,5 @@ import { describe, expect, it } from "vitest"; -import { - buildAuthHeaders, - getQoderBaseUrl, - getQoderCenterUrl, - getQoderChatURL, - getQoderExchangeURL, - getQoderManageUrl, - getQoderMode, - getQoderModelListURL, - getQoderOpenApiUrl, - getQoderRefreshURL, - getQoderUsageURL, - getQoderUserEmailFallback, - getQoderUserInfoURL, - isQoderCNMode, - toQoderModelId, -} from "../cosy.js"; - -// ── getQoderMode ────────────────────────────────────────────────────────── - -describe("getQoderMode", () => { - it('returns "cn" for explicit CN variants', () => { - expect(getQoderMode("cn")).toBe("cn"); - expect(getQoderMode("china")).toBe("cn"); - expect(getQoderMode("qodercn")).toBe("cn"); - expect(getQoderMode("qoder-cn")).toBe("cn"); - expect(getQoderMode("CN")).toBe("cn"); - expect(getQoderMode("China")).toBe("cn"); - }); - - it('returns "global" for explicit global variants', () => { - expect(getQoderMode("global")).toBe("global"); - expect(getQoderMode("intl")).toBe("global"); - expect(getQoderMode("international")).toBe("global"); - expect(getQoderMode("qoder")).toBe("global"); - }); - - it("falls back to global for unknown strings", () => { - expect(getQoderMode("unknown")).toBe("global"); - expect(getQoderMode("")).toBe("global"); - }); -}); - -// ── isQoderCNMode ───────────────────────────────────────────────────────── - -describe("isQoderCNMode", () => { - it("returns true for CN modes", () => { - expect(isQoderCNMode("cn")).toBe(true); - expect(isQoderCNMode("china")).toBe(true); - }); - - it("returns false for global modes", () => { - expect(isQoderCNMode("global")).toBe(false); - expect(isQoderCNMode("intl")).toBe(false); - }); -}); - -// ── URL builders ────────────────────────────────────────────────────────── - -describe("getQoderBaseUrl", () => { - it("returns CN URL for cn mode", () => { - expect(getQoderBaseUrl("cn")).toBe("https://gateway.qoder.com.cn/"); - }); - - it("returns global URL for global mode", () => { - expect(getQoderBaseUrl("global")).toBe("https://api3.qoder.sh/"); - }); -}); - -describe("getQoderOpenApiUrl", () => { - it("returns CN URL for cn mode", () => { - expect(getQoderOpenApiUrl("cn")).toBe("https://openapi.qoder.com.cn"); - }); - - it("returns global URL for global mode", () => { - expect(getQoderOpenApiUrl("global")).toBe("https://openapi.qoder.sh"); - }); -}); - -describe("getQoderCenterUrl", () => { - it("returns CN URL for cn mode", () => { - expect(getQoderCenterUrl("cn")).toBe("https://gateway.qoder.com.cn"); - }); - - it("returns global URL for global mode", () => { - expect(getQoderCenterUrl("global")).toBe("https://center.qoder.sh"); - }); -}); - -describe("getQoderModelListURL", () => { - it("constructs correct CN URL", () => { - expect(getQoderModelListURL("cn")).toBe("https://gateway.qoder.com.cn/algo/api/v2/model/list?Encode=1"); - }); - - it("constructs correct global URL", () => { - expect(getQoderModelListURL("global")).toBe("https://api3.qoder.sh/algo/api/v2/model/list?Encode=1"); - }); -}); - -describe("getQoderChatURL", () => { - it("contains base URL and chat path", () => { - const url = getQoderChatURL("global"); - expect(url).toContain("https://api3.qoder.sh/"); - expect(url).toContain("algo/api/v2/service/pro/sse/agent_chat_generation"); - expect(url).toContain("Encode=1"); - }); -}); - -describe("getQoderExchangeURL", () => { - it("constructs correct CN URL", () => { - expect(getQoderExchangeURL("cn")).toBe("https://openapi.qoder.com.cn/api/v1/jobToken/exchange"); - }); - - it("constructs correct global URL", () => { - expect(getQoderExchangeURL("global")).toBe("https://openapi.qoder.sh/api/v1/jobToken/exchange"); - }); -}); - -describe("getQoderUserInfoURL", () => { - it("constructs correct URL", () => { - expect(getQoderUserInfoURL("global")).toBe("https://openapi.qoder.sh/api/v1/userinfo"); - }); -}); - -describe("getQoderUsageURL", () => { - it("constructs correct URL", () => { - expect(getQoderUsageURL("global")).toBe("https://openapi.qoder.sh/api/v2/quota/usage"); - }); -}); - -describe("getQoderRefreshURL", () => { - it("constructs correct CN URL", () => { - expect(getQoderRefreshURL("cn")).toBe("https://gateway.qoder.com.cn/algo/api/v3/user/refresh_token"); - }); - - it("constructs correct global URL", () => { - expect(getQoderRefreshURL("global")).toBe("https://center.qoder.sh/algo/api/v3/user/refresh_token"); - }); -}); - -describe("getQoderManageUrl", () => { - it("returns CN URL", () => { - expect(getQoderManageUrl("cn")).toBe("https://qoder.com.cn"); - }); - - it("returns global URL", () => { - expect(getQoderManageUrl("global")).toBe("https://qoder.com"); - }); -}); - -describe("getQoderUserEmailFallback", () => { - it("returns CN email", () => { - expect(getQoderUserEmailFallback("cn")).toBe("user@qoder.com.cn"); - }); - - it("returns global email", () => { - expect(getQoderUserEmailFallback("global")).toBe("user@qoder.com"); - }); -}); - -// ── toQoderModelId ──────────────────────────────────────────────────────── - -describe("toQoderModelId", () => { - it("strips whitespace from the upstream display_name", () => { - // The display name is used directly as the pi-visible model id, with - // whitespace removed so it stays a clean token for persistence keys and - // search. "Qwen3.8-Flash" has no spaces already. - expect(toQoderModelId("Qwen3.8-Flash")).toBe("Qwen3.8-Flash"); - }); - - it("collapses internal spaces", () => { - expect(toQoderModelId("Qwen 3.8 Max")).toBe("Qwen3.8Max"); - expect(toQoderModelId("DeepSeek V4 Pro")).toBe("DeepSeekV4Pro"); - }); - - it("falls back to a default when no display name is given", () => { - expect(toQoderModelId()).toBe("QoderModel"); - expect(toQoderModelId("")).toBe("QoderModel"); - }); -}); +import { buildAuthHeaders } from "../cosy.js"; describe("COSY client identity", () => { it("sends Cosy-Version and cosyVersion as current qodercli 1.1.38", () => { diff --git a/src/__tests__/qoder-encoding.test.ts b/src/__tests__/encoding.test.ts similarity index 97% rename from src/__tests__/qoder-encoding.test.ts rename to src/__tests__/encoding.test.ts index 9f98d73..014f75f 100644 --- a/src/__tests__/qoder-encoding.test.ts +++ b/src/__tests__/encoding.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { qoderEncodeBody } from "../qoder-encoding.js"; +import { qoderEncodeBody } from "../protocol/encoding.js"; describe("qoderEncodeBody", () => { it("encodes a simple string", () => { diff --git a/src/__tests__/oauth.test.ts b/src/__tests__/oauth.test.ts index 10cd90f..b7643b3 100644 --- a/src/__tests__/oauth.test.ts +++ b/src/__tests__/oauth.test.ts @@ -2,14 +2,14 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { updateQoderModelsCache } from "../models.js"; -import { autoLoginQoderFromEnvironment, getCachedCredentials, getQoderPatForMode } from "../oauth.js"; -import { credentialsFromPat } from "../pat.js"; +import { updateQoderModelsCache } from "../catalog.js"; +import { autoLoginQoderFromEnvironment, getCachedCredentials, getQoderPatForMode } from "../auth/oauth.js"; +import { credentialsFromPat } from "../auth/pat.js"; import { loadLiveFixture } from "./live-fixture.js"; const AUTH_FILE = join(homedir(), ".pi", "agent", "auth.json"); -vi.mock("../pat.js", () => ({ +vi.mock("../auth/pat.js", () => ({ credentialsFromPat: vi.fn().mockResolvedValue({ access: "mock-access-token", refresh: "mock-refresh-token", @@ -24,7 +24,7 @@ vi.mock("../pat.js", () => ({ decodePatRefresh: vi.fn(), })); -vi.mock("../models.js", () => ({ +vi.mock("../catalog.js", () => ({ updateQoderModelsCache: vi.fn().mockResolvedValue(undefined), getCachedModels: vi.fn().mockReturnValue([]), isCacheStale: vi.fn().mockReturnValue(true), diff --git a/src/__tests__/pat.test.ts b/src/__tests__/pat.test.ts index 55a5716..1b8438c 100644 --- a/src/__tests__/pat.test.ts +++ b/src/__tests__/pat.test.ts @@ -6,7 +6,7 @@ import { fetchUserInfo, isPatRefresh, PAT_REFRESH_PREFIX, -} from "../pat.js"; +} from "../auth/pat.js"; import { loadLiveFixture, responseFromFixture } from "./live-fixture.js"; afterEach(() => { diff --git a/src/__tests__/providers.test.ts b/src/__tests__/providers.test.ts index 6783cdd..e75bff6 100644 --- a/src/__tests__/providers.test.ts +++ b/src/__tests__/providers.test.ts @@ -1,7 +1,6 @@ import type { OAuthCredentials } from "@earendil-works/pi-ai"; import { afterEach, describe, expect, it, vi } from "vitest"; -const originalRegion = process.env.QODER_REGION; const patEnvNames = [ "QODER_API_KEY", "QODER_PERSONAL_ACCESS_TOKEN", @@ -13,8 +12,6 @@ const patEnvNames = [ const originalPats = Object.fromEntries(patEnvNames.map((name) => [name, process.env[name]])); afterEach(() => { - if (originalRegion === undefined) delete process.env.QODER_REGION; - else process.env.QODER_REGION = originalRegion; for (const name of patEnvNames) { const value = originalPats[name]; if (value === undefined) delete process.env[name]; @@ -25,8 +22,7 @@ afterEach(() => { }); describe("provider region binding", () => { - it("keeps qoder global and qoder-cn in CN when QODER_REGION=cn", async () => { - process.env.QODER_REGION = "cn"; + it("binds qoder to global and qoder-cn to CN", async () => { for (const name of patEnvNames) delete process.env[name]; const providers = new Map>(); const pi = { diff --git a/src/__tests__/region.test.ts b/src/__tests__/region.test.ts new file mode 100644 index 0000000..ee8f47f --- /dev/null +++ b/src/__tests__/region.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { + getQoderBaseUrl, + getQoderChatURL, + getQoderExchangeURL, + getQoderModelListURL, + getQoderRefreshURL, + getQoderRegionConfig, + getQoderUsageURL, + getQoderUserInfoURL, + QODER_MODES, +} from "../region.js"; + +describe("Qoder regions", () => { + it("defines only the fixed global and CN provider bindings", () => { + expect(QODER_MODES).toEqual(["global", "cn"]); + expect(getQoderRegionConfig("global").providerID).toBe("qoder"); + expect(getQoderRegionConfig("cn").providerID).toBe("qoder-cn"); + }); + + it("builds global endpoints", () => { + expect(getQoderBaseUrl("global")).toBe("https://api3.qoder.sh/"); + expect(getQoderModelListURL("global")).toBe("https://api3.qoder.sh/algo/api/v2/model/list?Encode=1"); + expect(getQoderChatURL("global")).toContain("api3.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation"); + expect(getQoderExchangeURL("global")).toBe("https://openapi.qoder.sh/api/v1/jobToken/exchange"); + expect(getQoderUserInfoURL("global")).toBe("https://openapi.qoder.sh/api/v1/userinfo"); + expect(getQoderUsageURL("global")).toBe("https://openapi.qoder.sh/api/v2/quota/usage"); + expect(getQoderRefreshURL("global")).toBe("https://center.qoder.sh/algo/api/v3/user/refresh_token"); + }); + + it("builds CN endpoints", () => { + expect(getQoderBaseUrl("cn")).toBe("https://gateway.qoder.com.cn/"); + expect(getQoderModelListURL("cn")).toBe("https://gateway.qoder.com.cn/algo/api/v2/model/list?Encode=1"); + expect(getQoderChatURL("cn")).toContain("gateway.qoder.com.cn/algo/api/v2/service/pro/sse/agent_chat_generation"); + expect(getQoderExchangeURL("cn")).toBe("https://openapi.qoder.com.cn/api/v1/jobToken/exchange"); + expect(getQoderUserInfoURL("cn")).toBe("https://openapi.qoder.com.cn/api/v1/userinfo"); + expect(getQoderUsageURL("cn")).toBe("https://openapi.qoder.com.cn/api/v2/quota/usage"); + expect(getQoderRefreshURL("cn")).toBe("https://gateway.qoder.com.cn/algo/api/v3/user/refresh_token"); + }); +}); diff --git a/src/__tests__/stream.test.ts b/src/__tests__/stream.test.ts index 9cd9ca0..050f525 100644 --- a/src/__tests__/stream.test.ts +++ b/src/__tests__/stream.test.ts @@ -8,13 +8,13 @@ import type { ToolCall, } from "@earendil-works/pi-ai"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { streamQoder } from "../stream.js"; +import { streamQoder } from "../protocol/stream.js"; import { loadLiveFixture } from "./live-fixture.js"; // Pin the identity so the mocked fetch below only ever serves the chat request. // Without a resolved identity, streamQoder fetches /userinfo first and consumes // the mock response, leaving the chat read to fail on a locked stream. -vi.mock("../oauth.js", () => ({ +vi.mock("../auth/oauth.js", () => ({ resolveQoderIdentity: vi.fn().mockResolvedValue({ access: "fake", userID: "test-user", @@ -93,8 +93,8 @@ function mockFetch(body: string): typeof fetch { return vi.fn(async () => response) as unknown as typeof fetch; } -function makeModel(provider = "qoder"): Model { - return { id: "ultimate", api: "qoder-api" as Api, provider } as Model; +function makeModel(provider = "qoder", id = "Lite"): Model { + return { id, api: "qoder-api" as Api, provider } as Model; } function makeContext(): Context { @@ -137,6 +137,32 @@ describe("streamQoder", () => { expect(text && "text" in text ? text.text : "").toBe("OK"); }); + it("sends the internal upstream key for a friendly model id", async () => { + globalThis.fetch = mockFetch(SUCCESS_SSE); + await consume(streamQoder(makeModel("qoder", "Lite"), makeContext(), { apiKey: "fake" })); + + const init = vi.mocked(globalThis.fetch).mock.calls[0][1]; + expect(init?.headers).toEqual(expect.objectContaining({ "X-Model-Key": "lite" })); + + const custom = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!"; + const standard = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const encoded = Buffer.from(init?.body as Uint8Array).toString("utf8"); + const rearranged = [...encoded] + .map((character) => (character === "$" ? "=" : standard[custom.indexOf(character)] || character)) + .join(""); + const third = Math.floor(rearranged.length / 3); + const base64 = + rearranged.slice(rearranged.length - third) + + rearranged.slice(third, rearranged.length - third) + + rearranged.slice(0, third); + const body = JSON.parse(Buffer.from(base64, "base64").toString("utf8")) as { + chat_context: { extra: { modelConfig: { key: string } } }; + model_config: { key: string }; + }; + expect(body.chat_context.extra.modelConfig.key).toBe("lite"); + expect(body.model_config.key).toBe("lite"); + }); + it("binds chat hosts to provider ids even when only a CN PAT is set", async () => { process.env.QODERCN_PERSONAL_ACCESS_TOKEN = "pt-cn-only"; diff --git a/src/__tests__/thinking-parser.test.ts b/src/__tests__/thinking.test.ts similarity index 99% rename from src/__tests__/thinking-parser.test.ts rename to src/__tests__/thinking.test.ts index bce343d..23126ba 100644 --- a/src/__tests__/thinking-parser.test.ts +++ b/src/__tests__/thinking.test.ts @@ -1,6 +1,6 @@ import type { Api, AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream } from "@earendil-works/pi-ai"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { stripThinkingTags, ThinkingTagParser } from "../thinking-parser.js"; +import { stripThinkingTags, ThinkingTagParser } from "../protocol/thinking.js"; function createMockStream() { const events: AssistantMessageEvent[] = []; diff --git a/src/__tests__/transform.test.ts b/src/__tests__/transform.test.ts index 48fc0bd..2f56672 100644 --- a/src/__tests__/transform.test.ts +++ b/src/__tests__/transform.test.ts @@ -1,6 +1,6 @@ import type { Message, Tool } from "@earendil-works/pi-ai"; import { describe, expect, it } from "vitest"; -import { getContentText, transformMessagesForQoder, transformTools } from "../transform.js"; +import { getContentText, transformMessagesForQoder, transformTools } from "../protocol/transform.js"; // ── getContentText ──────────────────────────────────────────────────────── diff --git a/src/login.ts b/src/auth/login.ts similarity index 90% rename from src/login.ts rename to src/auth/login.ts index afa47a4..9ef066a 100644 --- a/src/login.ts +++ b/src/auth/login.ts @@ -1,6 +1,13 @@ import crypto from "node:crypto"; import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai"; -import { getMachineId, getQoderMode, getQoderRegionConfig } from "./cosy.js"; +import { getMachineId } from "../cosy.js"; +import { + getQoderDeviceLoginURL, + getQoderDevicePollURL, + getQoderRegionConfig, + getQoderUserInfoURL, + type QoderMode, +} from "../region.js"; import { credentialsFromPat } from "./pat.js"; type PromptFn = (p: { message: string; placeholder?: string; allowEmpty?: boolean }) => Promise; @@ -38,7 +45,7 @@ function parseExpiresAt(s?: string, expiresInSeconds?: number): number { export async function interactiveLogin( callbacks: OAuthLoginCallbacks, - mode: string = getQoderMode(), + mode: QoderMode, ): Promise { const region = getQoderRegionConfig(mode); // pi drives this via its built-in LoginDialog, which wires onPrompt/onAuth/ @@ -60,7 +67,7 @@ export async function interactiveLogin( if (!region.supportsBrowserLogin) { throw new Error( - "Qoder CN browser login is not supported here. Paste a Qoder CN PAT from https://qoder.com.cn/account/integrations or set QODERCN_PERSONAL_ACCESS_TOKEN.", + `Qoder CN browser login is not supported here. Paste a Qoder CN PAT from ${region.patManageUrl} or set QODERCN_PERSONAL_ACCESS_TOKEN.`, ); } @@ -71,8 +78,8 @@ export async function interactiveLogin( /** Prompt for a PAT (if not provided) and exchange it for full credentials. */ async function patLogin( callbacks: OAuthLoginCallbacks, - providedPat?: string, - mode: string = getQoderMode(), + providedPat: string | undefined, + mode: QoderMode, ): Promise { const region = getQoderRegionConfig(mode); let pat = providedPat; @@ -117,7 +124,7 @@ async function runDeviceFlow(callbacks: OAuthLoginCallbacks): Promise { +export async function autoLoginQoderFromEnvironment(providerID: string, mode: QoderMode): Promise { const pat = getQoderPatForMode(mode); if (!pat) return; @@ -118,7 +119,7 @@ const identityCache = new Map(); export async function resolveQoderIdentity( accessToken: string, providerID: string, - mode: string, + mode: QoderMode, ): Promise { const region = getQoderRegionConfig(mode); const cached = getCachedCredentials(accessToken, providerID); @@ -144,7 +145,7 @@ export async function resolveQoderIdentity( return creds; } -export async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: string): Promise { +export async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: QoderMode): Promise { const providerID = getQoderRegionConfig(mode).providerID; // 1. Try environment variables first (PAT). A PAT (pt-...) must be exchanged // for a short-lived job token before it can be used — credentialsFromPat @@ -182,7 +183,10 @@ export async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: st return creds; } -export async function refreshQoderTokenForMode(credentials: OAuthCredentials, mode: string): Promise { +export async function refreshQoderTokenForMode( + credentials: OAuthCredentials, + mode: QoderMode, +): Promise { // PAT-based credentials: re-exchange the stored PAT for a fresh job token. if (isPatRefresh(credentials.refresh)) { const { pat } = decodePatRefresh(credentials.refresh); diff --git a/src/pat.ts b/src/auth/pat.ts similarity index 92% rename from src/pat.ts rename to src/auth/pat.ts index cc3c551..8f62183 100644 --- a/src/pat.ts +++ b/src/auth/pat.ts @@ -1,13 +1,11 @@ import type { OAuthCredentials } from "@earendil-works/pi-ai"; +import { getMachineId, QODER_CLIENT_TYPE, QODER_OPENAPI_COSY_VERSION } from "../cosy.js"; import { - getMachineId, getQoderExchangeURL, - getQoderMode, getQoderRegionConfig, getQoderUserInfoURL, - QODER_CLIENT_TYPE, - QODER_OPENAPI_COSY_VERSION, -} from "./cosy.js"; + type QoderMode, +} from "../region.js"; const UA = "pi-provider-qoder"; @@ -57,7 +55,7 @@ export function decodePatRefresh(refresh: string): { * POST /api/v1/jobToken/exchange { personal_token } -> { token, refresh_token, expires_at } * The exchange endpoint does not require a COSY signature. */ -export async function exchangeJobToken(pat: string, mode: string = getQoderMode()): Promise { +export async function exchangeJobToken(pat: string, mode: QoderMode): Promise { const res = await fetch(getQoderExchangeURL(mode), { method: "POST", headers: { @@ -105,7 +103,7 @@ export async function exchangeJobToken(pat: string, mode: string = getQoderMode( /** Fetch user profile using a job token (jt-...). Best-effort. */ export async function fetchUserInfo( jobToken: string, - mode: string, + mode: QoderMode, ): Promise<{ userID: string; email: string; name: string }> { let userID = ""; let email = ""; @@ -140,7 +138,7 @@ export async function fetchUserInfo( * Exchanges the PAT for a job token, resolves identity, and encodes the PAT * into the refresh field so the token can be re-exchanged on expiry. */ -export async function credentialsFromPat(pat: string, mode: string = getQoderMode()): Promise { +export async function credentialsFromPat(pat: string, mode: QoderMode): Promise { const region = getQoderRegionConfig(mode); const { jobToken, jobRefreshToken, expiresAt } = await exchangeJobToken(pat, mode); const { userID, email, name } = await fetchUserInfo(jobToken, mode); diff --git a/src/usage.ts b/src/auth/usage.ts similarity index 91% rename from src/usage.ts rename to src/auth/usage.ts index 14fa94c..25b92c8 100644 --- a/src/usage.ts +++ b/src/auth/usage.ts @@ -1,5 +1,5 @@ import type { OAuthCredentials } from "@earendil-works/pi-ai"; -import { getQoderRegionConfig, getQoderUsageURL } from "./cosy.js"; +import { getQoderRegionConfig, getQoderUsageURL, type QoderMode } from "../region.js"; interface QoderQuota { total: number; @@ -33,7 +33,10 @@ export interface QoderProviderUsage { raw?: Record; } -export async function fetchQoderUsageForMode(credentials: OAuthCredentials, mode: string): Promise { +export async function fetchQoderUsageForMode( + credentials: OAuthCredentials, + mode: QoderMode, +): Promise { const region = getQoderRegionConfig(mode); const response = await fetch(getQoderUsageURL(mode), { method: "GET", diff --git a/src/models.ts b/src/catalog.ts similarity index 90% rename from src/models.ts rename to src/catalog.ts index 2310d00..966d571 100644 --- a/src/models.ts +++ b/src/catalog.ts @@ -2,15 +2,13 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import type { ThinkingLevel, ThinkingLevelMap } from "@earendil-works/pi-ai"; +import { buildAuthHeaders } from "./cosy.js"; import { - buildAuthHeaders, getQoderBaseUrl, - getQoderMode, getQoderModelListURL, getQoderRegionConfig, - isQoderCNMode, - toQoderModelId, -} from "./cosy.js"; + type QoderMode, +} from "./region.js"; export const ZERO_COST = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }); @@ -71,10 +69,18 @@ export interface QoderModelDef { description?: string; } -function getQoderCachePath(mode?: string): string { +function getQoderCachePath(mode: QoderMode): string { return join(homedir(), ".pi", "agent", getQoderRegionConfig(mode).modelCacheFile); } +/** + * Derive the only public model id from Qoder's display name. + * The upstream key remains available solely inside the matching config entry. + */ +export function toQoderModelId(displayName?: string): string { + return (displayName || "QoderModel").replace(/\s+/g, ""); +} + export const staticModels: QoderModelDef[] = [ { id: "Auto", @@ -478,7 +484,7 @@ function buildThinkingLevelMap(entry: QoderModelEntry): ThinkingLevelMap | undef return undefined; } -export function getCachedModels(mode?: string): QoderModelDef[] { +export function getCachedModels(mode: QoderMode): QoderModelDef[] { const cachePath = getQoderCachePath(mode); if (existsSync(cachePath)) { try { @@ -487,7 +493,12 @@ export function getCachedModels(mode?: string): QoderModelDef[] { const models = data.models.map((model: QoderModelDef) => { const config = data.configs?.[model.id] as QoderModelEntry | undefined; const display = config?.display_name; - return display ? { ...model, id: toQoderModelId(display), name: display } : model; + const staticModel = (mode === "cn" ? staticCnModels : staticModels).find( + (seed) => seed.upstreamKey === model.id, + ); + if (display) return { ...model, id: toQoderModelId(display), name: display }; + if (staticModel) return { ...model, id: staticModel.id, name: staticModel.name }; + return model.name ? { ...model, id: toQoderModelId(model.name) } : model; }); // Older releases injected `auto` without a corresponding service config. // Keep an explicitly enabled service model, but drop the legacy fallback. @@ -498,38 +509,42 @@ export function getCachedModels(mode?: string): QoderModelDef[] { } } catch {} } - return isQoderCNMode(mode) ? staticCnModels : staticModels; + return mode === "cn" ? staticCnModels : staticModels; } -export function getCachedModelConfig(modelKey: string, mode?: string): QoderModelEntry | null { +export function getCachedModelConfig(modelId: string, mode: QoderMode): QoderModelEntry | null { const cachePath = getQoderCachePath(mode); if (existsSync(cachePath)) { try { const data = JSON.parse(readFileSync(cachePath, "utf8")); - if (data?.configs?.[modelKey]) { - return withMaxContextAsDefault(data.configs[modelKey] as QoderModelEntry); + const direct = data?.configs?.[modelId] as QoderModelEntry | undefined; + if (direct && toQoderModelId(direct.display_name) === modelId) { + return withMaxContextAsDefault(direct); + } + + // Read old cache shapes without preserving their raw-key aliases. + const legacyEntry = Object.values(data?.configs || {}).find( + (entry) => + entry && + typeof entry === "object" && + toQoderModelId((entry as QoderModelEntry).display_name) === modelId, + ) as QoderModelEntry | undefined; + if (legacyEntry) { + return withMaxContextAsDefault(legacyEntry); } } catch {} } - // Static catalogs expose friendly ids too. Preserve raw keys as request-time - // aliases so older commands and persisted selections continue to work. - const staticModel = (isQoderCNMode(mode) ? staticCnModels : staticModels).find( - (model) => model.id.toLowerCase() === modelKey.toLowerCase() || model.upstreamKey === modelKey, - ); + const staticModel = (mode === "cn" ? staticCnModels : staticModels).find((model) => model.id === modelId); if (staticModel) { return { - key: staticModel.upstreamKey || modelKey, + key: staticModel.upstreamKey || modelId, is_reasoning: staticModel.reasoning, source: "system", }; } - return { - key: modelKey, - is_reasoning: false, - source: "system", - }; + return null; } /** Resolve contextWindow from a catalog entry. Exported for tests. */ @@ -568,7 +583,7 @@ function withMaxContextAsDefault(entry: QoderModelEntry): QoderModelEntry { }; } -export function isCacheStale(mode?: string): boolean { +export function isCacheStale(mode: QoderMode): boolean { const cachePath = getQoderCachePath(mode); if (!existsSync(cachePath)) return true; try { @@ -586,7 +601,7 @@ export async function updateQoderModelsCache( userID: string, name: string, email: string, - mode: string = getQoderMode(), + mode: QoderMode, ): Promise { const modelListURL = getQoderModelListURL(mode); try { @@ -631,13 +646,12 @@ export async function updateQoderModelsCache( const isReasoning = !!entry.is_reasoning || !!entry.thinking_config; const supportsEffort = !!entry.thinking_config?.enabled?.efforts; const thinkingLevelMap = buildThinkingLevelMap(entry); - // Both regions expose display_name (whitespace-stripped) as the pi-visible - // id. The original key remains indexed in configs for request-time lookup - // and compatibility with old CLI/persisted model references. + // Both regions expose display_name (whitespace-stripped) as the sole + // pi-visible id. The config stores the upstream key under that id for + // request-time use. const modelInfo = { id: toQoderModelId(display), name: display }; - configs[key] = entry; - if (modelInfo.id !== key) configs[modelInfo.id] = entry; + configs[modelInfo.id] = entry; newModels.push({ id: modelInfo.id, diff --git a/src/cosy.ts b/src/cosy.ts index 5ea5cc4..ed3d53f 100644 --- a/src/cosy.ts +++ b/src/cosy.ts @@ -27,59 +27,6 @@ const QoderMachineOS = : "x86_64_linux"; const QoderMachineTypeMagic = "5"; -const QoderModeEnv = process.env.QODER_REGION || process.env.QODER_BACKEND || process.env.QODER_MODE || ""; - -export type QoderMode = "global" | "cn"; - -export interface QoderRegionConfig { - mode: QoderMode; - providerID: "qoder" | "qoder-cn"; - baseUrl: string; - openApiUrl: string; - centerUrl: string; - manageUrl: string; - modelCacheFile: string; - patEnvNames: readonly string[]; - loginName: string; - userNameFallback: string; - userEmailFallback: string; - usageTitle: string; - supportsBrowserLogin: boolean; -} - -const QODER_REGIONS: Record = { - global: { - mode: "global", - providerID: "qoder", - baseUrl: "https://api3.qoder.sh/", - openApiUrl: "https://openapi.qoder.sh", - centerUrl: "https://center.qoder.sh", - manageUrl: "https://qoder.com", - modelCacheFile: "qoder-models-cache.json", - patEnvNames: ["QODER_API_KEY", "QODER_PERSONAL_ACCESS_TOKEN", "QODER_PAT"], - loginName: "Qoder (Browser OAuth / PAT)", - userNameFallback: "Qoder User", - userEmailFallback: "user@qoder.com", - usageTitle: "Qoder AI Plan", - supportsBrowserLogin: true, - }, - cn: { - mode: "cn", - providerID: "qoder-cn", - baseUrl: "https://gateway.qoder.com.cn/", - openApiUrl: "https://openapi.qoder.com.cn", - centerUrl: "https://gateway.qoder.com.cn", - manageUrl: "https://qoder.com.cn", - modelCacheFile: "qoder-cn-models-cache.json", - patEnvNames: ["QODERCN_API_KEY", "QODERCN_PERSONAL_ACCESS_TOKEN", "QODERCN_PAT"], - loginName: "Qoder CN (PAT)", - userNameFallback: "Qoder CN User", - userEmailFallback: "user@qoder.com.cn", - usageTitle: "Qoder CN Plan", - supportsBrowserLogin: false, - }, -}; - interface UserInfo { uid: string; security_oauth_token: string; @@ -104,89 +51,6 @@ export interface CosyCredentials { machineID?: string; } -export function getQoderMode(modeOverride?: string): QoderMode { - const mode = (modeOverride || QoderModeEnv).toLowerCase(); - if (["cn", "china", "qodercn", "qoder-cn"].includes(mode)) return "cn"; - if (["global", "intl", "international", "qoder"].includes(mode)) return "global"; - if ( - (process.env.QODERCN_PERSONAL_ACCESS_TOKEN || process.env.QODERCN_PAT) && - !(process.env.QODER_PERSONAL_ACCESS_TOKEN || process.env.QODER_PAT) - ) { - return "cn"; - } - return "global"; -} - -export function isQoderCNMode(modeOverride?: string): boolean { - return getQoderMode(modeOverride) === "cn"; -} - -export function getQoderRegionConfig(mode?: string): QoderRegionConfig { - return QODER_REGIONS[getQoderMode(mode)]; -} - -export function getQoderBaseUrl(mode?: string): string { - return getQoderRegionConfig(mode).baseUrl; -} - -export function getQoderOpenApiUrl(mode?: string): string { - return getQoderRegionConfig(mode).openApiUrl; -} - -export function getQoderCenterUrl(mode?: string): string { - return getQoderRegionConfig(mode).centerUrl; -} - -export function getQoderModelListURL(mode?: string): string { - // The CLI uses Encode=1 for the model catalog. Without it, the service - // returns a reduced catalog and omits models such as Cantus/cmodel. - return `${getQoderBaseUrl(mode)}algo/api/v2/model/list?Encode=1`; -} - -export function getQoderChatURL(mode?: string): string { - return `${getQoderBaseUrl(mode)}algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1`; -} - -export function getQoderExchangeURL(mode?: string): string { - return `${getQoderOpenApiUrl(mode)}/api/v1/jobToken/exchange`; -} - -export function getQoderUserInfoURL(mode?: string): string { - return `${getQoderOpenApiUrl(mode)}/api/v1/userinfo`; -} - -export function getQoderUsageURL(mode?: string): string { - return `${getQoderOpenApiUrl(mode)}/api/v2/quota/usage`; -} - -export function getQoderRefreshURL(mode?: string): string { - return `${getQoderCenterUrl(mode)}/algo/api/v3/user/refresh_token`; -} - -/** - * Derive the model `id` pi exposes in the picker from Qoder's `display_name`. - * - * The picker renders `Model.id`, not `Model.name`, so the display name is used - * directly as the id (with whitespace stripped so it stays a clean token for - * persistence keys, logs, and search). The original upstream `key` (e.g. - * `qfmodel`) is NOT used as the id: it is kept only as the request-time - * identifier, read back from the cached model config at send time. This drops - * the hardcoded key<->friendlyId mapping tables entirely — the label now - * tracks whatever upstream returns, so a renamed/upgraded model is shown - * correctly without a code change. - */ -export function toQoderModelId(displayName?: string): string { - return (displayName || "QoderModel").replace(/\s+/g, ""); -} - -export function getQoderManageUrl(mode?: string): string { - return getQoderRegionConfig(mode).manageUrl; -} - -export function getQoderUserEmailFallback(mode?: string): string { - return getQoderRegionConfig(mode).userEmailFallback; -} - function rsaEncryptBase64(data: Buffer | string): string { const key = { key: qoderRSAPublicKey, diff --git a/src/index.ts b/src/index.ts index f849d5d..b792dd8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,15 @@ import type { Api, Model, OAuthCredentials } from "@earendil-works/pi-ai"; import type { ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent"; -import { getQoderBaseUrl, getQoderRegionConfig, isQoderCNMode } from "./cosy.js"; -import { getCachedModels, isCacheStale, staticCnModels, staticModels, updateQoderModelsCache } from "./models.js"; +import { getCachedModels, isCacheStale, staticCnModels, staticModels, updateQoderModelsCache } from "./catalog.js"; +import { getQoderBaseUrl, getQoderRegionConfig, QODER_MODES, type QoderMode } from "./region.js"; import { autoLoginQoderFromEnvironment, getCachedCredentials, loginQoderForMode, refreshQoderTokenForMode, -} from "./oauth.js"; -import { streamQoder } from "./stream.js"; -import { fetchQoderUsageForMode } from "./usage.js"; +} from "./auth/oauth.js"; +import { streamQoder } from "./protocol/stream.js"; +import { fetchQoderUsageForMode } from "./auth/usage.js"; // pi supports a `fetchUsage` hook on the oauth config at runtime, but it is not // part of the published ProviderConfig type. Declare the extension locally. @@ -17,9 +17,9 @@ type OAuthConfigWithUsage = NonNullable & { fetchUsage: (credentials: OAuthCredentials) => Promise; }; -function modelsForProvider(mode: string, providerID: string): Model[] { +function modelsForProvider(mode: QoderMode, providerID: string): Model[] { const cached = getCachedModels(mode); - const modelsToUse = cached.length > 0 ? cached : isQoderCNMode(mode) ? staticCnModels : staticModels; + const modelsToUse = cached.length > 0 ? cached : mode === "cn" ? staticCnModels : staticModels; return modelsToUse.map((m) => ({ ...m, @@ -28,7 +28,7 @@ function modelsForProvider(mode: string, providerID: string): Model[] { })) as unknown as Model[]; } -function createQoderOAuth(mode: string): OAuthConfigWithUsage { +function createQoderOAuth(mode: QoderMode): OAuthConfigWithUsage { const region = getQoderRegionConfig(mode); return { name: region.loginName, @@ -44,7 +44,8 @@ function createQoderOAuth(mode: string): OAuthConfigWithUsage { }; } -function registerQoderProvider(pi: ExtensionAPI, providerID: string, mode: string): void { +function registerQoderProvider(pi: ExtensionAPI, mode: QoderMode): void { + const providerID = getQoderRegionConfig(mode).providerID; const oauth = createQoderOAuth(mode); pi.registerProvider(providerID, { baseUrl: getQoderBaseUrl(mode), @@ -57,7 +58,8 @@ function registerQoderProvider(pi: ExtensionAPI, providerID: string, mode: strin }); } -async function refreshModelsAtStartup(providerID: string, mode: string): Promise { +async function refreshModelsAtStartup(mode: QoderMode): Promise { + const providerID = getQoderRegionConfig(mode).providerID; if (!isCacheStale(mode)) return; const credentials = getCachedCredentials("", providerID); @@ -74,13 +76,11 @@ async function refreshModelsAtStartup(providerID: string, mode: string): Promise } export default async function (pi: ExtensionAPI) { - for (const [providerID, mode] of [ - ["qoder", "global"], - ["qoder-cn", "cn"], - ] as const) { + for (const mode of QODER_MODES) { + const providerID = getQoderRegionConfig(mode).providerID; try { await autoLoginQoderFromEnvironment(providerID, mode); - await refreshModelsAtStartup(providerID, mode); + await refreshModelsAtStartup(mode); } catch (error) { const message = error instanceof Error ? error.message : String(error); console.error(`[pi-provider-qoder] Automatic login failed for ${providerID}: ${message}`); @@ -92,12 +92,10 @@ export default async function (pi: ExtensionAPI) { // Login/refresh are the other rebuild triggers; this covers the case where // the cache was deleted while the token is still valid. pi.on("session_start", async (_event, ctx) => { - for (const [providerID, mode] of [ - ["qoder", "global"], - ["qoder-cn", "cn"], - ] as const) { + for (const mode of QODER_MODES) { try { const region = getQoderRegionConfig(mode); + const providerID = region.providerID; const accessToken = await ctx.modelRegistry.getApiKeyForProvider(providerID); if (!accessToken || !isCacheStale(mode)) continue; const creds = getCachedCredentials(accessToken, providerID); @@ -111,6 +109,5 @@ export default async function (pi: ExtensionAPI) { } }); - registerQoderProvider(pi, "qoder", "global"); - registerQoderProvider(pi, "qoder-cn", "cn"); + for (const mode of QODER_MODES) registerQoderProvider(pi, mode); } diff --git a/src/qoder-encoding.ts b/src/protocol/encoding.ts similarity index 100% rename from src/qoder-encoding.ts rename to src/protocol/encoding.ts diff --git a/src/stream.ts b/src/protocol/stream.ts similarity index 97% rename from src/stream.ts rename to src/protocol/stream.ts index 59bb3b6..bcc9997 100644 --- a/src/stream.ts +++ b/src/protocol/stream.ts @@ -12,11 +12,12 @@ import { type ThinkingContent, type ToolCall, } from "@earendil-works/pi-ai"; -import { buildAuthHeaders, getMachineId, getQoderChatURL, getQoderRegionConfig, isQoderCNMode } from "./cosy.js"; -import { getCachedModelConfig, MAX_OUTPUT_TOKENS } from "./models.js"; -import { resolveQoderIdentity } from "./oauth.js"; -import { qoderEncodeBody } from "./qoder-encoding.js"; -import { stripThinkingTags, ThinkingTagParser } from "./thinking-parser.js"; +import { buildAuthHeaders, getMachineId } from "../cosy.js"; +import { getCachedModelConfig, MAX_OUTPUT_TOKENS } from "../catalog.js"; +import { resolveQoderIdentity } from "../auth/oauth.js"; +import { getQoderChatURL, getQoderRegionConfig } from "../region.js"; +import { qoderEncodeBody } from "./encoding.js"; +import { stripThinkingTags, ThinkingTagParser } from "./thinking.js"; import { transformMessagesForQoder, transformTools } from "./transform.js"; interface ToolCallState { @@ -115,7 +116,7 @@ export function streamQoder( const accessToken = options?.apiKey; if (!accessToken) { throw new Error( - isQoderCNMode(providerMode) + providerMode === "cn" ? "Qoder CN credentials not set. Run /login qoder-cn or set QODERCN_PERSONAL_ACCESS_TOKEN." : "Qoder credentials not set. Run /login qoder or set QODER_PERSONAL_ACCESS_TOKEN.", ); @@ -134,13 +135,11 @@ export function streamQoder( // Both providers expose the upstream display_name (whitespace stripped) // as the pi id. Read the original key from cached/static config so the // gateway still receives identifiers such as `lite` or `qmodel`. - const modelConfig = getCachedModelConfig(model.id, providerMode) || { - key: model.id, - is_reasoning: false, - source: "system", - }; - // Raw legacy keys are also indexed as aliases by the model config cache. - const qoderModel = modelConfig.key || model.id; + const modelConfig = getCachedModelConfig(model.id, providerMode); + if (!modelConfig?.key) { + throw new Error(`Unknown Qoder model id: ${model.id}`); + } + const qoderModel = modelConfig.key; const isReasoning = !!modelConfig.is_reasoning; diff --git a/src/thinking-parser.ts b/src/protocol/thinking.ts similarity index 100% rename from src/thinking-parser.ts rename to src/protocol/thinking.ts diff --git a/src/transform.ts b/src/protocol/transform.ts similarity index 100% rename from src/transform.ts rename to src/protocol/transform.ts diff --git a/src/region.ts b/src/region.ts new file mode 100644 index 0000000..3de483f --- /dev/null +++ b/src/region.ts @@ -0,0 +1,100 @@ +export type QoderMode = "global" | "cn"; + +export interface QoderRegionConfig { + mode: QoderMode; + providerID: "qoder" | "qoder-cn"; + baseUrl: string; + openApiUrl: string; + centerUrl: string; + manageUrl: string; + patManageUrl: string; + deviceLoginUrl?: string; + modelCacheFile: string; + patEnvNames: readonly string[]; + loginName: string; + userNameFallback: string; + userEmailFallback: string; + usageTitle: string; + supportsBrowserLogin: boolean; +} + +const QODER_REGIONS: Record = { + global: { + mode: "global", + providerID: "qoder", + baseUrl: "https://api3.qoder.sh/", + openApiUrl: "https://openapi.qoder.sh", + centerUrl: "https://center.qoder.sh", + manageUrl: "https://qoder.com", + patManageUrl: "https://qoder.com/account/integrations", + deviceLoginUrl: "https://qoder.com/device/selectAccounts", + modelCacheFile: "qoder-models-cache.json", + patEnvNames: ["QODER_API_KEY", "QODER_PERSONAL_ACCESS_TOKEN", "QODER_PAT"], + loginName: "Qoder (Browser OAuth / PAT)", + userNameFallback: "Qoder User", + userEmailFallback: "user@qoder.com", + usageTitle: "Qoder AI Plan", + supportsBrowserLogin: true, + }, + cn: { + mode: "cn", + providerID: "qoder-cn", + baseUrl: "https://gateway.qoder.com.cn/", + openApiUrl: "https://openapi.qoder.com.cn", + centerUrl: "https://gateway.qoder.com.cn", + manageUrl: "https://qoder.com.cn", + patManageUrl: "https://qoder.com.cn/account/integrations", + modelCacheFile: "qoder-cn-models-cache.json", + patEnvNames: ["QODERCN_API_KEY", "QODERCN_PERSONAL_ACCESS_TOKEN", "QODERCN_PAT"], + loginName: "Qoder CN (PAT)", + userNameFallback: "Qoder CN User", + userEmailFallback: "user@qoder.com.cn", + usageTitle: "Qoder CN Plan", + supportsBrowserLogin: false, + }, +}; + +export const QODER_MODES: readonly QoderMode[] = ["global", "cn"]; + +export function getQoderRegionConfig(mode: QoderMode): QoderRegionConfig { + return QODER_REGIONS[mode]; +} + +export function getQoderBaseUrl(mode: QoderMode): string { + return getQoderRegionConfig(mode).baseUrl; +} + +export function getQoderModelListURL(mode: QoderMode): string { + return `${getQoderBaseUrl(mode)}algo/api/v2/model/list?Encode=1`; +} + +export function getQoderChatURL(mode: QoderMode): string { + return `${getQoderBaseUrl(mode)}algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1`; +} + +export function getQoderExchangeURL(mode: QoderMode): string { + return `${getQoderRegionConfig(mode).openApiUrl}/api/v1/jobToken/exchange`; +} + +export function getQoderUserInfoURL(mode: QoderMode): string { + return `${getQoderRegionConfig(mode).openApiUrl}/api/v1/userinfo`; +} + +export function getQoderUsageURL(mode: QoderMode): string { + return `${getQoderRegionConfig(mode).openApiUrl}/api/v2/quota/usage`; +} + +export function getQoderRefreshURL(mode: QoderMode): string { + return `${getQoderRegionConfig(mode).centerUrl}/algo/api/v3/user/refresh_token`; +} + +export function getQoderDeviceLoginURL(codeChallenge: string, machineID: string, nonce: string): string { + const baseUrl = getQoderRegionConfig("global").deviceLoginUrl; + if (!baseUrl) throw new Error("Qoder browser login URL is not configured"); + return `${baseUrl}?challenge=${codeChallenge}&challenge_method=S256&machine_id=${machineID}&nonce=${nonce}`; +} + +export function getQoderDevicePollURL(nonce: string, codeVerifier: string): string { + const baseUrl = getQoderRegionConfig("global").openApiUrl; + return `${baseUrl}/api/v1/deviceToken/poll?nonce=${encodeURIComponent(nonce)}&verifier=${encodeURIComponent(codeVerifier)}&challenge_method=S256`; +}