Support Qoder CN (#4)

* feat(qoder-cn): add region endpoints and model catalog

* feat(qoder-cn): add separate provider auth and streaming

* docs: document Qoder CN provider
This commit is contained in:
温习江湖
2026-06-26 14:42:36 +08:00
committed by GitHub
parent d09feb9aec
commit 2b2f427628
9 changed files with 599 additions and 138 deletions
+129
View File
@@ -17,6 +17,10 @@ const QoderLoginVersion = "v2";
const QoderMachineOS = "x86_64_windows";
const QoderMachineTypeMagic = "5";
const QoderModeEnv = process.env.QODER_REGION || process.env.QODER_BACKEND || process.env.QODER_MODE || "";
export type QoderMode = "global" | "cn";
interface UserInfo {
uid: string;
security_oauth_token: string;
@@ -41,6 +45,131 @@ 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 getQoderCNPat(): string {
return process.env.QODERCN_PERSONAL_ACCESS_TOKEN || process.env.QODERCN_PAT || "";
}
export function getQoderBaseUrl(mode?: string): string {
return isQoderCNMode(mode) ? "https://gateway.qoder.com.cn/" : "https://api3.qoder.sh/";
}
export const QODER_CN_DIRECT_BASE_URL = getQoderBaseUrl("cn");
export function getQoderOpenApiUrl(mode?: string): string {
return isQoderCNMode(mode) ? "https://openapi.qoder.com.cn" : "https://openapi.qoder.sh";
}
export function getQoderCenterUrl(mode?: string): string {
return isQoderCNMode(mode) ? "https://gateway.qoder.com.cn" : "https://center.qoder.sh";
}
export function getQoderModelListURL(mode?: string): string {
return `${getQoderBaseUrl(mode)}algo/api/v2/model/list`;
}
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`;
}
export function getQoderCNDirectModel(modelID?: string): string {
return (
{
"qoder-cn": "auto",
"qwen3.7-max": "qmodel_latest",
"qwen3.7-plus": "qmodel",
"qwen3.6-plus": "qmodel",
"qwen3.6-flash": "q36fmodel",
"deepseek-v4-pro": "dmodel",
"deepseek-v4-flash": "dfmodel",
"glm-5.2": "gm51model",
"glm-5.1": "gm51model",
"kimi-k2.6": "kmodel",
"minimax-m2.7": "mmodel",
"minimax-m3": "mmodel",
}[modelID || ""] ||
modelID ||
"auto"
);
}
const qoderCNFriendlyModels: Record<string, { id: string; name: string }> = {
auto: { id: "auto", name: "Auto · Qoder CN" },
"qoder-cn": { id: "qoder-cn", name: "Auto · Qoder CN" },
qmodel_latest: { id: "qwen3.7-max", name: "Qwen 3.7 Max · Qoder CN" },
qmodel: { id: "qwen3.7-plus", name: "Qwen 3.7 Plus · Qoder CN" },
q36fmodel: { id: "qwen3.6-flash", name: "Qwen 3.6 Flash · Qoder CN" },
qfmodel: { id: "qwen3.6-flash", name: "Qwen 3.6 Flash · Qoder CN" },
dmodel: { id: "deepseek-v4-pro", name: "DeepSeek V4 Pro · Qoder CN" },
dfmodel: { id: "deepseek-v4-flash", name: "DeepSeek V4 Flash · Qoder CN" },
gm51model: { id: "glm-5.2", name: "GLM 5.2 · Qoder CN" },
kmodel: { id: "kimi-k2.6", name: "Kimi K2.6 · Qoder CN" },
mmodel: { id: "minimax-m2.7", name: "MiniMax M2.7 · Qoder CN" },
};
function prettifyQoderCNModelName(name: string): string {
const pretty = (name || "Qoder CN Model")
.replace(/Qwen(\d)/g, "Qwen $1")
.replace(/Qwen([\d.]+)-/g, "Qwen $1 ")
.replace(/DeepSeek\s*V(\d)-/g, "DeepSeek V$1 ")
.replace(/\s+/g, " ")
.trim();
return pretty.includes("Qoder CN") ? pretty : `${pretty} · Qoder CN`;
}
export function getQoderCNFriendlyModelInfo(key: string, display?: string): { id: string; name: string } {
return qoderCNFriendlyModels[key] || { id: key, name: prettifyQoderCNModelName(display || key) };
}
export function toQoderCNFriendlyModel<T extends { id: string; name: string }>(model: T): T {
const info = getQoderCNFriendlyModelInfo(model.id, model.name);
return {
...model,
id: info.id,
name: info.name,
};
}
export function getQoderManageUrl(mode?: string): string {
return isQoderCNMode(mode) ? "https://qoder.com.cn" : "https://qoder.com";
}
export function getQoderUserEmailFallback(mode?: string): string {
return isQoderCNMode(mode) ? "user@qoder.com.cn" : "user@qoder.com";
}
function rsaEncryptBase64(data: Buffer | string): string {
const key = {
key: qoderRSAPublicKey,
+67 -40
View File
@@ -1,59 +1,86 @@
import type { Api, Model, OAuthCredentials } from "@earendil-works/pi-ai";
import type { ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent";
import { getCachedModels, isCacheStale, staticModels, updateQoderModelsCache } from "./models.js";
import { getCachedCredentials, loginQoder, refreshQoderToken } from "./oauth.js";
import {
getQoderBaseUrl,
getQoderMode,
getQoderUserEmailFallback,
isQoderCNMode,
toQoderCNFriendlyModel,
} from "./cosy.js";
import { getCachedModels, isCacheStale, staticCnModels, staticModels, updateQoderModelsCache } from "./models.js";
import { getCachedCredentials, loginQoder, loginQoderCN, refreshQoderToken, refreshQoderTokenCN } from "./oauth.js";
import { streamQoder } from "./stream.js";
import { fetchQoderUsage } from "./usage.js";
import { fetchQoderUsage, fetchQoderUsageCN } from "./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.
type OAuthConfigWithUsage = NonNullable<ProviderConfig["oauth"]> & {
fetchUsage: typeof fetchQoderUsage;
fetchUsage: (credentials: OAuthCredentials) => Promise<unknown>;
};
function modelsForProvider(mode: string, providerID: string): Model<Api>[] {
const cached = getCachedModels(mode);
const modelsToUse = cached.length > 0 ? cached : isQoderCNMode(mode) ? staticCnModels : staticModels;
return modelsToUse.map((m) => {
const model = isQoderCNMode(mode) ? toQoderCNFriendlyModel(m) : m;
return {
...model,
provider: providerID,
baseUrl: getQoderBaseUrl(mode),
};
}) as unknown as Model<Api>[];
}
function createQoderOAuth(providerID: string, mode: string): OAuthConfigWithUsage {
return {
name: isQoderCNMode(mode) ? "Qoder CN (PAT)" : "Qoder (Browser OAuth / PAT)",
login: isQoderCNMode(mode) ? loginQoderCN : loginQoder,
refreshToken: isQoderCNMode(mode) ? refreshQoderTokenCN : refreshQoderToken,
getApiKey: (cred: OAuthCredentials) => cred.access,
modifyModels: (models: Model<Api>[], _cred: OAuthCredentials) => {
const nonQoder = models.filter((m: Model<Api>) => m.provider !== providerID);
return [...nonQoder, ...modelsForProvider(mode, providerID)];
},
fetchUsage: isQoderCNMode(mode) ? fetchQoderUsageCN : fetchQoderUsage,
};
}
function registerQoderProvider(pi: ExtensionAPI, providerID: string, mode: string): void {
const oauth = createQoderOAuth(providerID, mode);
pi.registerProvider(providerID, {
baseUrl: getQoderBaseUrl(mode),
api: "qoder-api" as Api,
models: modelsForProvider(mode, providerID) as unknown as ProviderConfig["models"],
oauth: oauth as ProviderConfig["oauth"],
streamSimple: streamQoder,
});
}
export default function (pi: ExtensionAPI) {
// Refresh the models cache once per session at startup if it is missing or
// stale (>1h old), rather than on every message in the stream hot path.
// 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) => {
try {
const accessToken = await ctx.modelRegistry.getApiKeyForProvider("qoder");
if (!accessToken || !isCacheStale()) return;
const creds = getCachedCredentials(accessToken);
const userID = creds?.userID || "qoder-user";
const name = creds?.name || "Qoder User";
const email = creds?.email || "user@qoder.com";
await updateQoderModelsCache(accessToken, userID, name, email);
} catch {
// Best-effort: fall back to the existing cache / static models.
for (const [providerID, mode] of [
["qoder", getQoderMode()],
["qoder-cn", "cn"],
] as const) {
try {
const accessToken = await ctx.modelRegistry.getApiKeyForProvider(providerID);
if (!accessToken || !isCacheStale(mode)) continue;
const creds = getCachedCredentials(accessToken, providerID);
const userID = creds?.userID || "qoder-user";
const name = creds?.name || (isQoderCNMode(mode) ? "Qoder CN User" : "Qoder User");
const email = creds?.email || getQoderUserEmailFallback(mode);
await updateQoderModelsCache(accessToken, userID, name, email, mode);
} catch {
// Best-effort: fall back to the existing cache / static models.
}
}
});
const oauth: OAuthConfigWithUsage = {
name: "Qoder (Browser OAuth / PAT)",
login: loginQoder,
refreshToken: refreshQoderToken,
getApiKey: (cred: OAuthCredentials) => cred.access,
modifyModels: (models: Model<Api>[], _cred: OAuthCredentials) => {
const cached = getCachedModels();
const nonQoder = models.filter((m: Model<Api>) => m.provider !== "qoder");
const modelsToUse = cached.length > 0 ? cached : staticModels;
const modifiedQoder = modelsToUse.map((m) => ({
...m,
baseUrl: "https://api3.qoder.sh/",
})) as Model<Api>[];
return [...nonQoder, ...modifiedQoder];
},
fetchUsage: fetchQoderUsage,
};
pi.registerProvider("qoder", {
baseUrl: "https://api3.qoder.sh/",
api: "qoder-api" as Api,
models: getCachedModels() as unknown as ProviderConfig["models"],
oauth: oauth as ProviderConfig["oauth"],
streamSimple: streamQoder,
});
registerQoderProvider(pi, "qoder", getQoderMode());
registerQoderProvider(pi, "qoder-cn", "cn");
}
+24 -7
View File
@@ -1,6 +1,6 @@
import crypto from "node:crypto";
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
import { getMachineId } from "./cosy.js";
import { getMachineId, getQoderMode, isQoderCNMode } from "./cosy.js";
import { credentialsFromPat } from "./pat.js";
type PromptFn = (p: { message: string; placeholder?: string; allowEmpty?: boolean }) => Promise<string>;
@@ -36,20 +36,31 @@ function parseExpiresAt(s?: string, expiresInSeconds?: number): number {
return Date.now() + 30 * 24 * 60 * 60 * 1000; // default 30 days
}
export async function interactiveLogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
export async function interactiveLogin(
callbacks: OAuthLoginCallbacks,
mode: string = getQoderMode(),
): Promise<OAuthCredentials> {
// pi drives this via its built-in LoginDialog, which wires onPrompt/onAuth/
// onProgress to a focused input. We must use those callbacks directly rather
// than opening our own ctx.ui.custom surface (which would steal focus and
// leave onPrompt unable to receive keystrokes).
const prompt = getPrompt(callbacks);
const pat = await prompt({
message: "Paste a Qoder Personal Access Token (pt-...), or leave empty for browser login",
message: isQoderCNMode(mode)
? "Paste a Qoder CN Personal Access Token, or leave empty to cancel"
: "Paste a Qoder Personal Access Token (pt-...), or leave empty for browser login",
placeholder: "pt-...",
allowEmpty: true,
});
if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled");
if (pat?.trim()) {
return patLogin(callbacks, pat.trim());
return patLogin(callbacks, pat.trim(), mode);
}
if (isQoderCNMode(mode)) {
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.",
);
}
if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled");
@@ -57,12 +68,18 @@ export async function interactiveLogin(callbacks: OAuthLoginCallbacks): Promise<
}
/** Prompt for a PAT (if not provided) and exchange it for full credentials. */
async function patLogin(callbacks: OAuthLoginCallbacks, providedPat?: string): Promise<OAuthCredentials> {
async function patLogin(
callbacks: OAuthLoginCallbacks,
providedPat?: string,
mode: string = getQoderMode(),
): Promise<OAuthCredentials> {
let pat = providedPat;
if (!pat) {
const prompt = getPrompt(callbacks);
const entered = await prompt({
message: "Paste your Qoder Personal Access Token (pt-...)",
message: isQoderCNMode(mode)
? "Paste your Qoder CN Personal Access Token"
: "Paste your Qoder Personal Access Token (pt-...)",
placeholder: "pt-...",
allowEmpty: false,
});
@@ -73,7 +90,7 @@ async function patLogin(callbacks: OAuthLoginCallbacks, providedPat?: string): P
throw new Error("No Personal Access Token provided");
}
getProgress(callbacks)?.("Exchanging access token...");
const creds = await credentialsFromPat(pat);
const creds = await credentialsFromPat(pat, mode);
getProgress(callbacks)?.("Login successful!");
return creds;
}
+204 -24
View File
@@ -1,9 +1,14 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { buildAuthHeaders } from "./cosy.js";
const CACHE_PATH = join(homedir(), ".pi", "agent", "qoder-models-cache.json");
import {
buildAuthHeaders,
getQoderBaseUrl,
getQoderCNFriendlyModelInfo,
getQoderMode,
getQoderModelListURL,
isQoderCNMode,
} from "./cosy.js";
export const ZERO_COST = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
@@ -26,7 +31,7 @@ export interface QoderModelDef {
id: string;
name: string;
api: "qoder-api";
provider: "qoder";
provider: "qoder" | "qoder-cn";
baseUrl: string;
reasoning: boolean;
supportsEffort: boolean;
@@ -34,6 +39,16 @@ export interface QoderModelDef {
cost: typeof ZERO_COST;
contextWindow: number;
maxTokens: number;
description?: string;
}
function getQoderCachePath(mode?: string): string {
return join(
homedir(),
".pi",
"agent",
isQoderCNMode(mode) ? "qoder-cn-models-cache.json" : "qoder-models-cache.json",
);
}
export const staticModels: QoderModelDef[] = [
@@ -195,34 +210,195 @@ export const staticModels: QoderModelDef[] = [
},
];
export function getCachedModels(): QoderModelDef[] {
if (existsSync(CACHE_PATH)) {
export const staticCnModels: QoderModelDef[] = [
{
id: "auto",
name: "Auto · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: true,
supportsEffort: false,
input: ["text", "image"],
cost: ZERO_COST,
contextWindow: 180000,
maxTokens: 32768,
description: "Qoder CN smart routing; live catalog reports 180K max input.",
},
{
id: "qwen3.7-max",
name: "Qwen 3.7 Max · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: true,
supportsEffort: false,
input: ["text", "image"],
cost: ZERO_COST,
contextWindow: 1000000,
maxTokens: 32768,
description: "Qoder CN qmodel_latest; context options 200K/400K/1M.",
},
{
id: "qwen3.7-plus",
name: "Qwen 3.7 Plus · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: true,
supportsEffort: false,
input: ["text"],
cost: ZERO_COST,
contextWindow: 1000000,
maxTokens: 32768,
description: "Qoder CN qmodel; context options 200K/400K/1M.",
},
{
id: "qwen3.6-flash",
name: "Qwen 3.6 Flash · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: true,
supportsEffort: false,
input: ["text"],
cost: ZERO_COST,
contextWindow: 1000000,
maxTokens: 32768,
description: "Qoder CN q36fmodel; context options 200K/400K/1M.",
},
{
id: "deepseek-v4-pro",
name: "DeepSeek V4 Pro · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: true,
supportsEffort: false,
input: ["text"],
cost: ZERO_COST,
contextWindow: 1000000,
maxTokens: 32768,
description: "Qoder CN dmodel; context options 200K/400K/1M.",
},
{
id: "deepseek-v4-flash",
name: "DeepSeek V4 Flash · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: false,
supportsEffort: false,
input: ["text"],
cost: ZERO_COST,
contextWindow: 1000000,
maxTokens: 32768,
description: "Qoder CN dfmodel; context options 200K/400K/1M.",
},
{
id: "glm-5.2",
name: "GLM 5.2 · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: true,
supportsEffort: false,
input: ["text", "image"],
cost: ZERO_COST,
contextWindow: 200000,
maxTokens: 32768,
description: "Qoder CN gm51model; live catalog currently displays GLM-5.2 with 200K context.",
},
{
id: "kimi-k2.6",
name: "Kimi K2.6 · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: true,
supportsEffort: false,
input: ["text", "image"],
cost: ZERO_COST,
contextWindow: 256000,
maxTokens: 32768,
description: "Qoder CN kmodel; context option 256K.",
},
{
id: "minimax-m2.7",
name: "MiniMax M2.7 · Qoder CN",
api: "qoder-api",
provider: "qoder-cn",
baseUrl: getQoderBaseUrl("cn"),
reasoning: false,
supportsEffort: false,
input: ["text"],
cost: ZERO_COST,
contextWindow: 200000,
maxTokens: 32768,
description: "Qoder CN mmodel; live catalog reports 200K context.",
},
];
export function getCachedModels(mode?: string): QoderModelDef[] {
const cachePath = getQoderCachePath(mode);
if (existsSync(cachePath)) {
try {
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
const data = JSON.parse(readFileSync(cachePath, "utf8"));
if (data && Array.isArray(data.models)) {
return data.models;
}
} catch {}
}
return staticModels;
return isQoderCNMode(mode) ? staticCnModels : staticModels;
}
export function getCachedModelConfig(modelKey: string): QoderModelEntry | null {
if (existsSync(CACHE_PATH)) {
export function getCachedModelConfig(modelKey: string, mode?: string): QoderModelEntry | null {
const cachePath = getQoderCachePath(mode);
if (existsSync(cachePath)) {
try {
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
const data = JSON.parse(readFileSync(cachePath, "utf8"));
if (data?.configs?.[modelKey]) {
return data.configs[modelKey] as QoderModelEntry;
}
} catch {}
}
if (isQoderCNMode(mode)) {
const reasoningModels = new Set([
"qoder-cn",
"auto",
"qmodel_latest",
"qmodel",
"q36fmodel",
"qfmodel",
"dmodel",
"gm51model",
"kmodel",
"qwen3.7-max",
"qwen3.7-plus",
"qwen3.6-plus",
"qwen3.6-flash",
"deepseek-v4-pro",
"glm-5.2",
"glm-5.1",
"kimi-k2.6",
]);
return {
key: modelKey,
is_reasoning: reasoningModels.has(modelKey),
max_output_tokens: 32768,
source: "system",
};
}
return null;
}
export function isCacheStale(): boolean {
if (!existsSync(CACHE_PATH)) return true;
export function isCacheStale(mode?: string): boolean {
const cachePath = getQoderCachePath(mode);
if (!existsSync(cachePath)) return true;
try {
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
const data = JSON.parse(readFileSync(cachePath, "utf8"));
if (!data || typeof data.updatedAt !== "number") return true;
// Stale if older than 1 hour
return Date.now() - data.updatedAt > 3600_000;
@@ -236,8 +412,9 @@ export async function updateQoderModelsCache(
userID: string,
name: string,
email: string,
mode: string = getQoderMode(),
): Promise<void> {
const modelListURL = "https://api3.qoder.sh/algo/api/v2/model/list";
const modelListURL = getQoderModelListURL(mode);
try {
const headers = buildAuthHeaders(null, modelListURL, {
userID,
@@ -284,15 +461,17 @@ export async function updateQoderModelsCache(
const isVL = !!entry.is_vl;
const isReasoning = !!entry.is_reasoning || !!entry.thinking_config;
const supportsEffort = !!entry.thinking_config?.enabled?.efforts;
const modelInfo = isQoderCNMode(mode) ? getQoderCNFriendlyModelInfo(key, display) : { id: key, name: display };
configs[key] = entry;
if (modelInfo.id !== key) configs[modelInfo.id] = entry;
newModels.push({
id: key,
name: display,
id: modelInfo.id,
name: modelInfo.name,
api: "qoder-api",
provider: "qoder",
baseUrl: "https://api3.qoder.sh/",
provider: isQoderCNMode(mode) ? "qoder-cn" : "qoder",
baseUrl: getQoderBaseUrl(mode),
reasoning: isReasoning,
supportsEffort,
input: isVL ? ["text", "image"] : ["text"],
@@ -308,10 +487,10 @@ export async function updateQoderModelsCache(
if (!newModels.some((m) => m.id === "auto")) {
newModels.unshift({
id: "auto",
name: "Qoder Auto",
name: isQoderCNMode(mode) ? "Auto · Qoder CN" : "Qoder Auto",
api: "qoder-api",
provider: "qoder",
baseUrl: "https://api3.qoder.sh/",
provider: isQoderCNMode(mode) ? "qoder-cn" : "qoder",
baseUrl: getQoderBaseUrl(mode),
reasoning: true,
supportsEffort: false,
input: ["text", "image"],
@@ -327,7 +506,8 @@ export async function updateQoderModelsCache(
configs,
};
mkdirSync(dirname(CACHE_PATH), { recursive: true });
writeFileSync(CACHE_PATH, JSON.stringify(cacheData, null, 2), "utf-8");
const cachePath = getQoderCachePath(mode);
mkdirSync(dirname(cachePath), { recursive: true });
writeFileSync(cachePath, JSON.stringify(cacheData, null, 2), "utf-8");
} catch {}
}
+30 -14
View File
@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
import { getMachineId } from "./cosy.js";
import { getMachineId, getQoderCNPat, getQoderMode, getQoderRefreshURL, isQoderCNMode } from "./cosy.js";
import { interactiveLogin } from "./login.js";
import { updateQoderModelsCache } from "./models.js";
import { credentialsFromPat, decodePatRefresh, isPatRefresh } from "./pat.js";
@@ -24,11 +24,11 @@ const AUTH_FILE = join(homedir(), ".pi", "agent", "auth.json");
* Note: the auth.json path/shape is a pi internal convention, not a public API.
* This is best-effort and falls back to null so callers can use placeholders.
*/
export function getCachedCredentials(_accessToken: string): QoderCredentials | null {
export function getCachedCredentials(_accessToken: string, providerID = "qoder"): QoderCredentials | null {
if (existsSync(AUTH_FILE)) {
try {
const auth = JSON.parse(readFileSync(AUTH_FILE, "utf-8"));
const creds = auth?.qoder;
const creds = auth?.[providerID] || (providerID === "qoder" ? auth?.qoder : null);
if (creds?.userID) {
return creds as QoderCredentials;
}
@@ -37,45 +37,61 @@ export function getCachedCredentials(_accessToken: string): QoderCredentials | n
return null;
}
export async function loginQoder(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: string): Promise<OAuthCredentials> {
// 1. Try environment variables first (PAT). A PAT (pt-...) must be exchanged
// for a short-lived job token before it can be used — credentialsFromPat
// handles the exchange + identity resolution.
const pat = process.env.QODER_PERSONAL_ACCESS_TOKEN || process.env.QODER_PAT;
const pat = isQoderCNMode(mode) ? getQoderCNPat() : process.env.QODER_PERSONAL_ACCESS_TOKEN || process.env.QODER_PAT;
if (pat) {
try {
const creds = await credentialsFromPat(pat);
const creds = await credentialsFromPat(pat, mode);
const qCreds = creds as QoderCredentials;
// pi persists these credentials in auth.json itself; no separate cache needed.
// Cache models in background
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email).catch(() => {});
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode).catch(() => {});
return creds;
} catch {
// Fall through to interactive login if PAT exchange fails.
}
}
// 2. Interactive login
const creds = await interactiveLogin(callbacks);
// 2. Interactive login (CN only supports PAT prompt here; global supports device flow fallback)
const creds = await interactiveLogin(callbacks, mode);
// Cache models in background. pi persists the credentials in auth.json itself.
try {
const qCreds = creds as QoderCredentials;
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email).catch(() => {});
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode).catch(() => {});
} catch {}
return creds;
}
export async function loginQoder(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
return loginQoderForMode(callbacks, getQoderMode());
}
export async function loginQoderCN(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
return loginQoderForMode(callbacks, "cn");
}
export async function refreshQoderToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
return refreshQoderTokenForMode(credentials, getQoderMode());
}
export async function refreshQoderTokenCN(credentials: OAuthCredentials): Promise<OAuthCredentials> {
return refreshQoderTokenForMode(credentials, "cn");
}
async function refreshQoderTokenForMode(credentials: OAuthCredentials, mode: string): Promise<OAuthCredentials> {
// PAT-based credentials: re-exchange the stored PAT for a fresh job token.
if (isPatRefresh(credentials.refresh)) {
const { pat } = decodePatRefresh(credentials.refresh);
if (pat) {
try {
const refreshed = await credentialsFromPat(pat);
const refreshed = await credentialsFromPat(pat, mode);
const qCreds = refreshed as QoderCredentials;
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email).catch(() => {});
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode).catch(() => {});
return refreshed;
} catch {
// Fall through to validity extension below.
@@ -95,7 +111,7 @@ export async function refreshQoderToken(credentials: OAuthCredentials): Promise<
const prevName = prev.name || "";
const prevEmail = prev.email || "";
const refreshURL = "https://center.qoder.sh/algo/api/v3/user/refresh_token";
const refreshURL = getQoderRefreshURL(mode);
try {
const response = await fetch(refreshURL, {
method: "POST",
@@ -140,7 +156,7 @@ export async function refreshQoderToken(credentials: OAuthCredentials): Promise<
// pi persists the refreshed credentials in auth.json itself.
// Cache models in background
updateQoderModelsCache(newAccess, userID, prevName, prevEmail).catch(() => {});
updateQoderModelsCache(newAccess, userID, prevName, prevEmail, mode).catch(() => {});
return refreshed;
}
+19 -14
View File
@@ -1,9 +1,14 @@
import type { OAuthCredentials } from "@earendil-works/pi-ai";
import { getMachineId } from "./cosy.js";
import {
getMachineId,
getQoderExchangeURL,
getQoderMode,
getQoderUserEmailFallback,
getQoderUserInfoURL,
isQoderCNMode,
} from "./cosy.js";
const UA = "pi-provider-qoder";
const EXCHANGE_URL = "https://openapi.qoder.sh/api/v1/jobToken/exchange";
const USERINFO_URL = "https://openapi.qoder.sh/api/v1/userinfo";
/**
* Marker prefix used in the credential `refresh` field to identify PAT-based
@@ -47,12 +52,12 @@ export function decodePatRefresh(refresh: string): {
/**
* Exchange a Qoder Personal Access Token (pt-...) for a short-lived Job Token
* (jt-...). PATs cannot authenticate API calls directly; they must first be
* exchanged. This mirrors the official qodercli flow:
* POST /api/v1/jobToken/exchange { personal_token } -> { token, refresh_token, expires_at }
* exchanged. This mirrors the official qodercli/qoderclicn flow:
* 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): Promise<PatExchangeResult> {
const res = await fetch(EXCHANGE_URL, {
export async function exchangeJobToken(pat: string, mode: string = getQoderMode()): Promise<PatExchangeResult> {
const res = await fetch(getQoderExchangeURL(mode), {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -97,12 +102,12 @@ export async function exchangeJobToken(pat: string): Promise<PatExchangeResult>
}
/** Fetch user profile using a job token (jt-...). Best-effort. */
async function fetchUserInfo(jobToken: string): Promise<{ userID: string; email: string; name: string }> {
async function fetchUserInfo(jobToken: string, mode: string): Promise<{ userID: string; email: string; name: string }> {
let userID = "";
let email = "";
let name = "";
try {
const res = await fetch(USERINFO_URL, {
const res = await fetch(getQoderUserInfoURL(mode), {
headers: {
Authorization: `Bearer ${jobToken}`,
Accept: "application/json",
@@ -131,9 +136,9 @@ async function fetchUserInfo(jobToken: string): Promise<{ userID: string; email:
* 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): Promise<OAuthCredentials> {
const { jobToken, jobRefreshToken, expiresAt } = await exchangeJobToken(pat);
const { userID, email, name } = await fetchUserInfo(jobToken);
export async function credentialsFromPat(pat: string, mode: string = getQoderMode()): Promise<OAuthCredentials> {
const { jobToken, jobRefreshToken, expiresAt } = await exchangeJobToken(pat, mode);
const { userID, email, name } = await fetchUserInfo(jobToken, mode);
const machineID = getMachineId();
return {
@@ -141,8 +146,8 @@ export async function credentialsFromPat(pat: string): Promise<OAuthCredentials>
access: jobToken,
expires: expiresAt - 5 * 60 * 1000, // 5 min buffer
userID,
email,
name,
email: email || getQoderUserEmailFallback(mode),
name: name || (isQoderCNMode(mode) ? "Qoder CN User" : "Qoder User"),
machineID,
} as OAuthCredentials;
}
+21 -9
View File
@@ -11,7 +11,15 @@ import type {
ToolCall,
} from "@earendil-works/pi-ai";
import * as PiAi from "@earendil-works/pi-ai";
import { buildAuthHeaders, getMachineId } from "./cosy.js";
import {
buildAuthHeaders,
getMachineId,
getQoderChatURL,
getQoderCNDirectModel,
getQoderMode,
getQoderUserEmailFallback,
isQoderCNMode,
} from "./cosy.js";
import { getCachedModelConfig } from "./models.js";
import { getCachedCredentials } from "./oauth.js";
import { qoderEncodeBody } from "./qoder-encoding.js";
@@ -95,20 +103,25 @@ export function streamQoder(
(async () => {
try {
const providerMode = model.provider === "qoder-cn" ? "cn" : getQoderMode();
const accessToken = options?.apiKey;
if (!accessToken) {
throw new Error("Qoder credentials not set. Run /login qoder or set QODER_PERSONAL_ACCESS_TOKEN.");
throw new Error(
isQoderCNMode(providerMode)
? "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.",
);
}
// Resolve user details from cached credentials
const cachedCreds = getCachedCredentials(accessToken);
const cachedCreds = getCachedCredentials(accessToken, model.provider);
const userID = cachedCreds?.userID || "qoder-user";
const name = cachedCreds?.name || "Qoder User";
const email = cachedCreds?.email || "user@qoder.com";
const name = cachedCreds?.name || (isQoderCNMode(providerMode) ? "Qoder CN User" : "Qoder User");
const email = cachedCreds?.email || getQoderUserEmailFallback(providerMode);
const machineID = cachedCreds?.machineID || getMachineId();
const qoderModel = model.id;
const modelConfig = getCachedModelConfig(qoderModel) || {
const qoderModel = isQoderCNMode(providerMode) ? getQoderCNDirectModel(model.id) : model.id;
const modelConfig = getCachedModelConfig(qoderModel, providerMode) || {
key: qoderModel,
is_reasoning:
qoderModel === "ultimate" ||
@@ -205,8 +218,7 @@ export function streamQoder(
const encodedBody = qoderEncodeBody(bodyBytes);
const encodedBytes = Buffer.from(encodedBody, "utf8");
const chatURL =
"https://api3.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1";
const chatURL = getQoderChatURL(providerMode);
const headers = buildAuthHeaders(encodedBytes, chatURL, {
userID,
+13 -5
View File
@@ -1,4 +1,5 @@
import type { OAuthCredentials } from "@earendil-works/pi-ai";
import { getQoderManageUrl, getQoderMode, getQoderUsageURL, isQoderCNMode } from "./cosy.js";
interface QoderQuota {
total: number;
@@ -32,9 +33,8 @@ export interface QoderProviderUsage {
raw?: Record<string, unknown>;
}
export async function fetchQoderUsage(credentials: OAuthCredentials): Promise<QoderProviderUsage> {
const usageURL = "https://openapi.qoder.sh/api/v2/quota/usage";
const response = await fetch(usageURL, {
async function fetchQoderUsageForMode(credentials: OAuthCredentials, mode: string): Promise<QoderProviderUsage> {
const response = await fetch(getQoderUsageURL(mode), {
method: "GET",
headers: {
Authorization: `Bearer ${credentials.access}`,
@@ -76,10 +76,18 @@ export async function fetchQoderUsage(credentials: OAuthCredentials): Promise<Qo
return {
summary: remainingText,
subscriptionTitle: "Qoder AI Plan",
subscriptionTitle: isQoderCNMode(mode) ? "Qoder CN Plan" : "Qoder AI Plan",
resetAt: raw.expiresAt ? new Date(raw.expiresAt).toISOString() : undefined,
manageUrl: "https://qoder.com",
manageUrl: getQoderManageUrl(mode),
usageBuckets,
raw: raw as unknown as Record<string, unknown>,
};
}
export async function fetchQoderUsage(credentials: OAuthCredentials): Promise<QoderProviderUsage> {
return fetchQoderUsageForMode(credentials, getQoderMode());
}
export async function fetchQoderUsageCN(credentials: OAuthCredentials): Promise<QoderProviderUsage> {
return fetchQoderUsageForMode(credentials, "cn");
}