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:
@@ -1,10 +1,14 @@
|
|||||||
# pi-provider-qoder
|
# pi-provider-qoder
|
||||||
|
|
||||||
A [pi](https://shittycodingagent.ai/) provider extension that connects pi to the **Qoder API**, exposing Qoder models through one provider surface.
|
A [pi](https://shittycodingagent.ai/) provider extension that connects pi to the **Qoder API**, exposing Qoder Global and Qoder China models through provider surfaces.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Interactive Login**: Standard OAuth browser device-code flow or Personal Access Token (PAT) login.
|
- **Two provider entries**:
|
||||||
|
- `qoder` — Global / international Qoder.
|
||||||
|
- `qoder-cn` — Qoder China, forced to CN endpoints and independent of `QODER_REGION`.
|
||||||
|
- **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`).
|
- **WAF Bypass**: Built-in WAF obfuscation and body encoding (`Encode=1`).
|
||||||
- **COSY Signing**: Full COSY signature header generation (RSA/AES-CBC/MD5).
|
- **COSY Signing**: Full COSY signature header generation (RSA/AES-CBC/MD5).
|
||||||
- **Dynamic Model Catalog**: Dynamically fetches model limits, effort configurations, and options from the `/algo/api/v2/model/list` endpoint.
|
- **Dynamic Model Catalog**: Dynamically fetches model limits, effort configurations, and options from the `/algo/api/v2/model/list` endpoint.
|
||||||
@@ -24,69 +28,132 @@ Or install it globally with npm:
|
|||||||
npm install -g pi-provider-qoder
|
npm install -g pi-provider-qoder
|
||||||
```
|
```
|
||||||
|
|
||||||
Then log in from pi:
|
Then log in from pi.
|
||||||
|
|
||||||
|
Global / international edition:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/login qoder
|
/login qoder
|
||||||
```
|
```
|
||||||
|
|
||||||
The login menu offers two methods:
|
China edition:
|
||||||
|
|
||||||
- **Browser Login** — OAuth device-code flow; complete authorization in your browser.
|
```text
|
||||||
- **Use API Key (PAT)** — paste a Qoder Personal Access Token (`pt-...`).
|
/login qoder-cn
|
||||||
|
```
|
||||||
|
|
||||||
### Personal Access Token (PAT)
|
### Personal Access Token (PAT)
|
||||||
|
|
||||||
A Qoder PAT (`pt-...`) cannot authenticate API calls directly — the provider
|
A Qoder PAT (`pt-...`) cannot authenticate API calls directly — the provider
|
||||||
exchanges it for a short-lived job token (mirroring the official `qodercli`
|
exchanges it for a short-lived job token (mirroring the official `qodercli` /
|
||||||
flow) and resolves your account identity automatically. You can supply a PAT in
|
`qoderclicn` flow) and resolves your account identity automatically.
|
||||||
two ways:
|
|
||||||
|
Global Qoder:
|
||||||
|
|
||||||
- Run `/login qoder` and choose **Use API Key (PAT)**, then paste the token.
|
- Run `/login qoder` and choose **Use API Key (PAT)**, then paste the token.
|
||||||
- Set the `QODER_PERSONAL_ACCESS_TOKEN` (or `QODER_PAT`) environment variable,
|
- Or set `QODER_PERSONAL_ACCESS_TOKEN` (or `QODER_PAT`) before starting pi.
|
||||||
then run `/login qoder` — the PAT is picked up automatically and exchanged
|
|
||||||
without further prompts. This is the recommended path for headless/CI setups.
|
Qoder China:
|
||||||
|
|
||||||
|
- Run `/login qoder-cn`, then paste the CN PAT.
|
||||||
|
- Or set `QODERCN_PERSONAL_ACCESS_TOKEN` (or `QODERCN_PAT`) before starting pi.
|
||||||
|
|
||||||
> The exchanged job token is short-lived; the provider transparently re-exchanges
|
> The exchanged job token is short-lived; the provider transparently re-exchanges
|
||||||
> the stored PAT when it expires.
|
> 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:
|
||||||
|
|
||||||
|
- PAT exchange: `https://openapi.qoder.sh/api/v1/jobToken/exchange`
|
||||||
|
- User info: `https://openapi.qoder.sh/api/v1/userinfo`
|
||||||
|
- Usage: `https://openapi.qoder.sh/api/v2/quota/usage`
|
||||||
|
- Model / chat gateway: `https://api3.qoder.sh/algo/api/v2/...`
|
||||||
|
|
||||||
|
China:
|
||||||
|
|
||||||
|
- PAT exchange: `https://openapi.qoder.com.cn/api/v1/jobToken/exchange`
|
||||||
|
- User info: `https://openapi.qoder.com.cn/api/v1/userinfo`
|
||||||
|
- Usage: `https://openapi.qoder.com.cn/api/v2/quota/usage`
|
||||||
|
- Model / chat gateway: `https://gateway.qoder.com.cn/algo/api/v2/...`
|
||||||
|
|
||||||
## Models
|
## Models
|
||||||
|
|
||||||
Exposes the following backing models:
|
### Global `qoder`
|
||||||
|
|
||||||
- **Tier Tiers**: `auto`, `ultimate`, `performance`, `efficient`, `lite`
|
Exposes the backing model keys returned by Qoder, including:
|
||||||
|
|
||||||
|
- **Tier Models**: `auto`, `ultimate`, `performance`, `efficient`, `lite`
|
||||||
- **Frontier Models**:
|
- **Frontier Models**:
|
||||||
- `qmodel` (Qwen3.7 Plus)
|
- `qmodel` (Qwen3.7 Plus)
|
||||||
- `qmodel_latest` (Qwen3.7 Max)
|
- `qmodel_latest` (Qwen3.7 Max)
|
||||||
- `dmodel` (DeepSeek V4 Pro)
|
- `dmodel` (DeepSeek V4 Pro)
|
||||||
- `dfmodel` (DeepSeek V4 Flash)
|
- `dfmodel` (DeepSeek V4 Flash)
|
||||||
- `gm51model` (GLM 5.1)
|
- `gm51model` (GLM)
|
||||||
- `kmodel` (Kimi K2.6)
|
- `kmodel` (Kimi)
|
||||||
- `mmodel` (MiniMax M3)
|
- `mmodel` (MiniMax)
|
||||||
|
|
||||||
|
### China `qoder-cn`
|
||||||
|
|
||||||
|
The China provider exposes friendly model IDs and maps them back to Qoder CN's
|
||||||
|
internal keys at request time:
|
||||||
|
|
||||||
|
| Friendly ID | Qoder CN key | Context | Images | Reasoning |
|
||||||
|
| --- | --- | ---: | :---: | :---: |
|
||||||
|
| `auto` | `auto` | 180K | ✅ | ✅ |
|
||||||
|
| `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`.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Once logged in, select any Qoder model in pi:
|
Once logged in, select any Qoder model in pi:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/model ultimate
|
/model qwen3.7-plus
|
||||||
```
|
```
|
||||||
|
|
||||||
Or let Qoder select automatically:
|
Or start directly:
|
||||||
|
|
||||||
```text
|
```bash
|
||||||
/model auto
|
pi --provider qoder-cn --model qwen3.7-plus
|
||||||
|
```
|
||||||
|
|
||||||
|
Global example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pi --provider qoder --model auto
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
```
|
```text
|
||||||
src/
|
src/
|
||||||
├── index.ts # Extension registration
|
├── index.ts # Extension registration
|
||||||
├── cosy.ts # COSY Signature and Machine ID resolver
|
├── cosy.ts # COSY signature, machine ID, region/endpoints, CN model aliases
|
||||||
├── login.ts # OAuth Device Flow + PAT login sequence
|
├── login.ts # OAuth device flow + PAT login sequence
|
||||||
├── pat.ts # PAT → job-token exchange + identity resolution
|
├── pat.ts # PAT → job-token exchange + identity resolution
|
||||||
├── models.ts # Model definitions and Dynamic Config Cache
|
├── models.ts # Model definitions and dynamic config cache
|
||||||
├── oauth.ts # PAT / OAuth callback orchestrator
|
├── oauth.ts # PAT / OAuth callback orchestrator
|
||||||
├── stream.ts # Main streaming response handler
|
├── stream.ts # Main streaming response handler
|
||||||
├── transform.ts # Message conversions (OpenAI schema mapping)
|
├── transform.ts # Message conversions (OpenAI schema mapping)
|
||||||
|
|||||||
+129
@@ -17,6 +17,10 @@ const QoderLoginVersion = "v2";
|
|||||||
const QoderMachineOS = "x86_64_windows";
|
const QoderMachineOS = "x86_64_windows";
|
||||||
const QoderMachineTypeMagic = "5";
|
const QoderMachineTypeMagic = "5";
|
||||||
|
|
||||||
|
const QoderModeEnv = process.env.QODER_REGION || process.env.QODER_BACKEND || process.env.QODER_MODE || "";
|
||||||
|
|
||||||
|
export type QoderMode = "global" | "cn";
|
||||||
|
|
||||||
interface UserInfo {
|
interface UserInfo {
|
||||||
uid: string;
|
uid: string;
|
||||||
security_oauth_token: string;
|
security_oauth_token: string;
|
||||||
@@ -41,6 +45,131 @@ export interface CosyCredentials {
|
|||||||
machineID?: string;
|
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 {
|
function rsaEncryptBase64(data: Buffer | string): string {
|
||||||
const key = {
|
const key = {
|
||||||
key: qoderRSAPublicKey,
|
key: qoderRSAPublicKey,
|
||||||
|
|||||||
+67
-40
@@ -1,59 +1,86 @@
|
|||||||
import type { Api, Model, OAuthCredentials } from "@earendil-works/pi-ai";
|
import type { Api, Model, OAuthCredentials } from "@earendil-works/pi-ai";
|
||||||
import type { ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent";
|
import type { ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent";
|
||||||
import { getCachedModels, isCacheStale, staticModels, updateQoderModelsCache } from "./models.js";
|
import {
|
||||||
import { getCachedCredentials, loginQoder, refreshQoderToken } from "./oauth.js";
|
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 { 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
|
// 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.
|
// part of the published ProviderConfig type. Declare the extension locally.
|
||||||
type OAuthConfigWithUsage = NonNullable<ProviderConfig["oauth"]> & {
|
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) {
|
export default function (pi: ExtensionAPI) {
|
||||||
// Refresh the models cache once per session at startup if it is missing or
|
// 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.
|
// 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
|
// Login/refresh are the other rebuild triggers; this covers the case where
|
||||||
// the cache was deleted while the token is still valid.
|
// the cache was deleted while the token is still valid.
|
||||||
pi.on("session_start", async (_event, ctx) => {
|
pi.on("session_start", async (_event, ctx) => {
|
||||||
try {
|
for (const [providerID, mode] of [
|
||||||
const accessToken = await ctx.modelRegistry.getApiKeyForProvider("qoder");
|
["qoder", getQoderMode()],
|
||||||
if (!accessToken || !isCacheStale()) return;
|
["qoder-cn", "cn"],
|
||||||
const creds = getCachedCredentials(accessToken);
|
] as const) {
|
||||||
const userID = creds?.userID || "qoder-user";
|
try {
|
||||||
const name = creds?.name || "Qoder User";
|
const accessToken = await ctx.modelRegistry.getApiKeyForProvider(providerID);
|
||||||
const email = creds?.email || "user@qoder.com";
|
if (!accessToken || !isCacheStale(mode)) continue;
|
||||||
await updateQoderModelsCache(accessToken, userID, name, email);
|
const creds = getCachedCredentials(accessToken, providerID);
|
||||||
} catch {
|
const userID = creds?.userID || "qoder-user";
|
||||||
// Best-effort: fall back to the existing cache / static models.
|
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 = {
|
registerQoderProvider(pi, "qoder", getQoderMode());
|
||||||
name: "Qoder (Browser OAuth / PAT)",
|
registerQoderProvider(pi, "qoder-cn", "cn");
|
||||||
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,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-7
@@ -1,6 +1,6 @@
|
|||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
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";
|
import { credentialsFromPat } from "./pat.js";
|
||||||
|
|
||||||
type PromptFn = (p: { message: string; placeholder?: string; allowEmpty?: boolean }) => Promise<string>;
|
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
|
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/
|
// pi drives this via its built-in LoginDialog, which wires onPrompt/onAuth/
|
||||||
// onProgress to a focused input. We must use those callbacks directly rather
|
// 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
|
// than opening our own ctx.ui.custom surface (which would steal focus and
|
||||||
// leave onPrompt unable to receive keystrokes).
|
// leave onPrompt unable to receive keystrokes).
|
||||||
const prompt = getPrompt(callbacks);
|
const prompt = getPrompt(callbacks);
|
||||||
const pat = await prompt({
|
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-...",
|
placeholder: "pt-...",
|
||||||
allowEmpty: true,
|
allowEmpty: true,
|
||||||
});
|
});
|
||||||
if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled");
|
if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled");
|
||||||
if (pat?.trim()) {
|
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");
|
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. */
|
/** 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;
|
let pat = providedPat;
|
||||||
if (!pat) {
|
if (!pat) {
|
||||||
const prompt = getPrompt(callbacks);
|
const prompt = getPrompt(callbacks);
|
||||||
const entered = await prompt({
|
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-...",
|
placeholder: "pt-...",
|
||||||
allowEmpty: false,
|
allowEmpty: false,
|
||||||
});
|
});
|
||||||
@@ -73,7 +90,7 @@ async function patLogin(callbacks: OAuthLoginCallbacks, providedPat?: string): P
|
|||||||
throw new Error("No Personal Access Token provided");
|
throw new Error("No Personal Access Token provided");
|
||||||
}
|
}
|
||||||
getProgress(callbacks)?.("Exchanging access token...");
|
getProgress(callbacks)?.("Exchanging access token...");
|
||||||
const creds = await credentialsFromPat(pat);
|
const creds = await credentialsFromPat(pat, mode);
|
||||||
getProgress(callbacks)?.("Login successful!");
|
getProgress(callbacks)?.("Login successful!");
|
||||||
return creds;
|
return creds;
|
||||||
}
|
}
|
||||||
|
|||||||
+204
-24
@@ -1,9 +1,14 @@
|
|||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
import { buildAuthHeaders } from "./cosy.js";
|
import {
|
||||||
|
buildAuthHeaders,
|
||||||
const CACHE_PATH = join(homedir(), ".pi", "agent", "qoder-models-cache.json");
|
getQoderBaseUrl,
|
||||||
|
getQoderCNFriendlyModelInfo,
|
||||||
|
getQoderMode,
|
||||||
|
getQoderModelListURL,
|
||||||
|
isQoderCNMode,
|
||||||
|
} from "./cosy.js";
|
||||||
|
|
||||||
export const ZERO_COST = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
export const ZERO_COST = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
||||||
|
|
||||||
@@ -26,7 +31,7 @@ export interface QoderModelDef {
|
|||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
api: "qoder-api";
|
api: "qoder-api";
|
||||||
provider: "qoder";
|
provider: "qoder" | "qoder-cn";
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
reasoning: boolean;
|
reasoning: boolean;
|
||||||
supportsEffort: boolean;
|
supportsEffort: boolean;
|
||||||
@@ -34,6 +39,16 @@ export interface QoderModelDef {
|
|||||||
cost: typeof ZERO_COST;
|
cost: typeof ZERO_COST;
|
||||||
contextWindow: number;
|
contextWindow: number;
|
||||||
maxTokens: 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[] = [
|
export const staticModels: QoderModelDef[] = [
|
||||||
@@ -195,34 +210,195 @@ export const staticModels: QoderModelDef[] = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export function getCachedModels(): QoderModelDef[] {
|
export const staticCnModels: QoderModelDef[] = [
|
||||||
if (existsSync(CACHE_PATH)) {
|
{
|
||||||
|
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 {
|
try {
|
||||||
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
|
const data = JSON.parse(readFileSync(cachePath, "utf8"));
|
||||||
if (data && Array.isArray(data.models)) {
|
if (data && Array.isArray(data.models)) {
|
||||||
return data.models;
|
return data.models;
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
return staticModels;
|
return isQoderCNMode(mode) ? staticCnModels : staticModels;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCachedModelConfig(modelKey: string): QoderModelEntry | null {
|
export function getCachedModelConfig(modelKey: string, mode?: string): QoderModelEntry | null {
|
||||||
if (existsSync(CACHE_PATH)) {
|
const cachePath = getQoderCachePath(mode);
|
||||||
|
if (existsSync(cachePath)) {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
|
const data = JSON.parse(readFileSync(cachePath, "utf8"));
|
||||||
if (data?.configs?.[modelKey]) {
|
if (data?.configs?.[modelKey]) {
|
||||||
return data.configs[modelKey] as QoderModelEntry;
|
return data.configs[modelKey] as QoderModelEntry;
|
||||||
}
|
}
|
||||||
} catch {}
|
} 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;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isCacheStale(): boolean {
|
export function isCacheStale(mode?: string): boolean {
|
||||||
if (!existsSync(CACHE_PATH)) return true;
|
const cachePath = getQoderCachePath(mode);
|
||||||
|
if (!existsSync(cachePath)) return true;
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
|
const data = JSON.parse(readFileSync(cachePath, "utf8"));
|
||||||
if (!data || typeof data.updatedAt !== "number") return true;
|
if (!data || typeof data.updatedAt !== "number") return true;
|
||||||
// Stale if older than 1 hour
|
// Stale if older than 1 hour
|
||||||
return Date.now() - data.updatedAt > 3600_000;
|
return Date.now() - data.updatedAt > 3600_000;
|
||||||
@@ -236,8 +412,9 @@ export async function updateQoderModelsCache(
|
|||||||
userID: string,
|
userID: string,
|
||||||
name: string,
|
name: string,
|
||||||
email: string,
|
email: string,
|
||||||
|
mode: string = getQoderMode(),
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const modelListURL = "https://api3.qoder.sh/algo/api/v2/model/list";
|
const modelListURL = getQoderModelListURL(mode);
|
||||||
try {
|
try {
|
||||||
const headers = buildAuthHeaders(null, modelListURL, {
|
const headers = buildAuthHeaders(null, modelListURL, {
|
||||||
userID,
|
userID,
|
||||||
@@ -284,15 +461,17 @@ export async function updateQoderModelsCache(
|
|||||||
const isVL = !!entry.is_vl;
|
const isVL = !!entry.is_vl;
|
||||||
const isReasoning = !!entry.is_reasoning || !!entry.thinking_config;
|
const isReasoning = !!entry.is_reasoning || !!entry.thinking_config;
|
||||||
const supportsEffort = !!entry.thinking_config?.enabled?.efforts;
|
const supportsEffort = !!entry.thinking_config?.enabled?.efforts;
|
||||||
|
const modelInfo = isQoderCNMode(mode) ? getQoderCNFriendlyModelInfo(key, display) : { id: key, name: display };
|
||||||
|
|
||||||
configs[key] = entry;
|
configs[key] = entry;
|
||||||
|
if (modelInfo.id !== key) configs[modelInfo.id] = entry;
|
||||||
|
|
||||||
newModels.push({
|
newModels.push({
|
||||||
id: key,
|
id: modelInfo.id,
|
||||||
name: display,
|
name: modelInfo.name,
|
||||||
api: "qoder-api",
|
api: "qoder-api",
|
||||||
provider: "qoder",
|
provider: isQoderCNMode(mode) ? "qoder-cn" : "qoder",
|
||||||
baseUrl: "https://api3.qoder.sh/",
|
baseUrl: getQoderBaseUrl(mode),
|
||||||
reasoning: isReasoning,
|
reasoning: isReasoning,
|
||||||
supportsEffort,
|
supportsEffort,
|
||||||
input: isVL ? ["text", "image"] : ["text"],
|
input: isVL ? ["text", "image"] : ["text"],
|
||||||
@@ -308,10 +487,10 @@ export async function updateQoderModelsCache(
|
|||||||
if (!newModels.some((m) => m.id === "auto")) {
|
if (!newModels.some((m) => m.id === "auto")) {
|
||||||
newModels.unshift({
|
newModels.unshift({
|
||||||
id: "auto",
|
id: "auto",
|
||||||
name: "Qoder Auto",
|
name: isQoderCNMode(mode) ? "Auto · Qoder CN" : "Qoder Auto",
|
||||||
api: "qoder-api",
|
api: "qoder-api",
|
||||||
provider: "qoder",
|
provider: isQoderCNMode(mode) ? "qoder-cn" : "qoder",
|
||||||
baseUrl: "https://api3.qoder.sh/",
|
baseUrl: getQoderBaseUrl(mode),
|
||||||
reasoning: true,
|
reasoning: true,
|
||||||
supportsEffort: false,
|
supportsEffort: false,
|
||||||
input: ["text", "image"],
|
input: ["text", "image"],
|
||||||
@@ -327,7 +506,8 @@ export async function updateQoderModelsCache(
|
|||||||
configs,
|
configs,
|
||||||
};
|
};
|
||||||
|
|
||||||
mkdirSync(dirname(CACHE_PATH), { recursive: true });
|
const cachePath = getQoderCachePath(mode);
|
||||||
writeFileSync(CACHE_PATH, JSON.stringify(cacheData, null, 2), "utf-8");
|
mkdirSync(dirname(cachePath), { recursive: true });
|
||||||
|
writeFileSync(cachePath, JSON.stringify(cacheData, null, 2), "utf-8");
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|||||||
+30
-14
@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
|
|||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
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 { interactiveLogin } from "./login.js";
|
||||||
import { updateQoderModelsCache } from "./models.js";
|
import { updateQoderModelsCache } from "./models.js";
|
||||||
import { credentialsFromPat, decodePatRefresh, isPatRefresh } from "./pat.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.
|
* 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.
|
* 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)) {
|
if (existsSync(AUTH_FILE)) {
|
||||||
try {
|
try {
|
||||||
const auth = JSON.parse(readFileSync(AUTH_FILE, "utf-8"));
|
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) {
|
if (creds?.userID) {
|
||||||
return creds as QoderCredentials;
|
return creds as QoderCredentials;
|
||||||
}
|
}
|
||||||
@@ -37,45 +37,61 @@ export function getCachedCredentials(_accessToken: string): QoderCredentials | n
|
|||||||
return null;
|
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
|
// 1. Try environment variables first (PAT). A PAT (pt-...) must be exchanged
|
||||||
// for a short-lived job token before it can be used — credentialsFromPat
|
// for a short-lived job token before it can be used — credentialsFromPat
|
||||||
// handles the exchange + identity resolution.
|
// 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) {
|
if (pat) {
|
||||||
try {
|
try {
|
||||||
const creds = await credentialsFromPat(pat);
|
const creds = await credentialsFromPat(pat, mode);
|
||||||
const qCreds = creds as QoderCredentials;
|
const qCreds = creds as QoderCredentials;
|
||||||
// pi persists these credentials in auth.json itself; no separate cache needed.
|
// pi persists these credentials in auth.json itself; no separate cache needed.
|
||||||
// Cache models in background
|
// 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;
|
return creds;
|
||||||
} catch {
|
} catch {
|
||||||
// Fall through to interactive login if PAT exchange fails.
|
// Fall through to interactive login if PAT exchange fails.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Interactive login
|
// 2. Interactive login (CN only supports PAT prompt here; global supports device flow fallback)
|
||||||
const creds = await interactiveLogin(callbacks);
|
const creds = await interactiveLogin(callbacks, mode);
|
||||||
|
|
||||||
// Cache models in background. pi persists the credentials in auth.json itself.
|
// Cache models in background. pi persists the credentials in auth.json itself.
|
||||||
try {
|
try {
|
||||||
const qCreds = creds as QoderCredentials;
|
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 {}
|
} catch {}
|
||||||
|
|
||||||
return creds;
|
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> {
|
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.
|
// PAT-based credentials: re-exchange the stored PAT for a fresh job token.
|
||||||
if (isPatRefresh(credentials.refresh)) {
|
if (isPatRefresh(credentials.refresh)) {
|
||||||
const { pat } = decodePatRefresh(credentials.refresh);
|
const { pat } = decodePatRefresh(credentials.refresh);
|
||||||
if (pat) {
|
if (pat) {
|
||||||
try {
|
try {
|
||||||
const refreshed = await credentialsFromPat(pat);
|
const refreshed = await credentialsFromPat(pat, mode);
|
||||||
const qCreds = refreshed as QoderCredentials;
|
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;
|
return refreshed;
|
||||||
} catch {
|
} catch {
|
||||||
// Fall through to validity extension below.
|
// Fall through to validity extension below.
|
||||||
@@ -95,7 +111,7 @@ export async function refreshQoderToken(credentials: OAuthCredentials): Promise<
|
|||||||
const prevName = prev.name || "";
|
const prevName = prev.name || "";
|
||||||
const prevEmail = prev.email || "";
|
const prevEmail = prev.email || "";
|
||||||
|
|
||||||
const refreshURL = "https://center.qoder.sh/algo/api/v3/user/refresh_token";
|
const refreshURL = getQoderRefreshURL(mode);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(refreshURL, {
|
const response = await fetch(refreshURL, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -140,7 +156,7 @@ export async function refreshQoderToken(credentials: OAuthCredentials): Promise<
|
|||||||
|
|
||||||
// pi persists the refreshed credentials in auth.json itself.
|
// pi persists the refreshed credentials in auth.json itself.
|
||||||
// Cache models in background
|
// Cache models in background
|
||||||
updateQoderModelsCache(newAccess, userID, prevName, prevEmail).catch(() => {});
|
updateQoderModelsCache(newAccess, userID, prevName, prevEmail, mode).catch(() => {});
|
||||||
|
|
||||||
return refreshed;
|
return refreshed;
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-14
@@ -1,9 +1,14 @@
|
|||||||
import type { OAuthCredentials } from "@earendil-works/pi-ai";
|
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 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
|
* 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
|
* Exchange a Qoder Personal Access Token (pt-...) for a short-lived Job Token
|
||||||
* (jt-...). PATs cannot authenticate API calls directly; they must first be
|
* (jt-...). PATs cannot authenticate API calls directly; they must first be
|
||||||
* exchanged. This mirrors the official qodercli flow:
|
* exchanged. This mirrors the official qodercli/qoderclicn flow:
|
||||||
* POST /api/v1/jobToken/exchange { personal_token } -> { token, refresh_token, expires_at }
|
* POST /api/v1/jobToken/exchange { personal_token } -> { token, refresh_token, expires_at }
|
||||||
* The exchange endpoint does not require a COSY signature.
|
* The exchange endpoint does not require a COSY signature.
|
||||||
*/
|
*/
|
||||||
export async function exchangeJobToken(pat: string): Promise<PatExchangeResult> {
|
export async function exchangeJobToken(pat: string, mode: string = getQoderMode()): Promise<PatExchangeResult> {
|
||||||
const res = await fetch(EXCHANGE_URL, {
|
const res = await fetch(getQoderExchangeURL(mode), {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"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. */
|
/** 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 userID = "";
|
||||||
let email = "";
|
let email = "";
|
||||||
let name = "";
|
let name = "";
|
||||||
try {
|
try {
|
||||||
const res = await fetch(USERINFO_URL, {
|
const res = await fetch(getQoderUserInfoURL(mode), {
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${jobToken}`,
|
Authorization: `Bearer ${jobToken}`,
|
||||||
Accept: "application/json",
|
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
|
* 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.
|
* into the refresh field so the token can be re-exchanged on expiry.
|
||||||
*/
|
*/
|
||||||
export async function credentialsFromPat(pat: string): Promise<OAuthCredentials> {
|
export async function credentialsFromPat(pat: string, mode: string = getQoderMode()): Promise<OAuthCredentials> {
|
||||||
const { jobToken, jobRefreshToken, expiresAt } = await exchangeJobToken(pat);
|
const { jobToken, jobRefreshToken, expiresAt } = await exchangeJobToken(pat, mode);
|
||||||
const { userID, email, name } = await fetchUserInfo(jobToken);
|
const { userID, email, name } = await fetchUserInfo(jobToken, mode);
|
||||||
const machineID = getMachineId();
|
const machineID = getMachineId();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -141,8 +146,8 @@ export async function credentialsFromPat(pat: string): Promise<OAuthCredentials>
|
|||||||
access: jobToken,
|
access: jobToken,
|
||||||
expires: expiresAt - 5 * 60 * 1000, // 5 min buffer
|
expires: expiresAt - 5 * 60 * 1000, // 5 min buffer
|
||||||
userID,
|
userID,
|
||||||
email,
|
email: email || getQoderUserEmailFallback(mode),
|
||||||
name,
|
name: name || (isQoderCNMode(mode) ? "Qoder CN User" : "Qoder User"),
|
||||||
machineID,
|
machineID,
|
||||||
} as OAuthCredentials;
|
} as OAuthCredentials;
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-9
@@ -11,7 +11,15 @@ import type {
|
|||||||
ToolCall,
|
ToolCall,
|
||||||
} from "@earendil-works/pi-ai";
|
} from "@earendil-works/pi-ai";
|
||||||
import * as PiAi 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 { getCachedModelConfig } from "./models.js";
|
||||||
import { getCachedCredentials } from "./oauth.js";
|
import { getCachedCredentials } from "./oauth.js";
|
||||||
import { qoderEncodeBody } from "./qoder-encoding.js";
|
import { qoderEncodeBody } from "./qoder-encoding.js";
|
||||||
@@ -95,20 +103,25 @@ export function streamQoder(
|
|||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
|
const providerMode = model.provider === "qoder-cn" ? "cn" : getQoderMode();
|
||||||
const accessToken = options?.apiKey;
|
const accessToken = options?.apiKey;
|
||||||
if (!accessToken) {
|
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
|
// Resolve user details from cached credentials
|
||||||
const cachedCreds = getCachedCredentials(accessToken);
|
const cachedCreds = getCachedCredentials(accessToken, model.provider);
|
||||||
const userID = cachedCreds?.userID || "qoder-user";
|
const userID = cachedCreds?.userID || "qoder-user";
|
||||||
const name = cachedCreds?.name || "Qoder User";
|
const name = cachedCreds?.name || (isQoderCNMode(providerMode) ? "Qoder CN User" : "Qoder User");
|
||||||
const email = cachedCreds?.email || "user@qoder.com";
|
const email = cachedCreds?.email || getQoderUserEmailFallback(providerMode);
|
||||||
const machineID = cachedCreds?.machineID || getMachineId();
|
const machineID = cachedCreds?.machineID || getMachineId();
|
||||||
|
|
||||||
const qoderModel = model.id;
|
const qoderModel = isQoderCNMode(providerMode) ? getQoderCNDirectModel(model.id) : model.id;
|
||||||
const modelConfig = getCachedModelConfig(qoderModel) || {
|
const modelConfig = getCachedModelConfig(qoderModel, providerMode) || {
|
||||||
key: qoderModel,
|
key: qoderModel,
|
||||||
is_reasoning:
|
is_reasoning:
|
||||||
qoderModel === "ultimate" ||
|
qoderModel === "ultimate" ||
|
||||||
@@ -205,8 +218,7 @@ export function streamQoder(
|
|||||||
const encodedBody = qoderEncodeBody(bodyBytes);
|
const encodedBody = qoderEncodeBody(bodyBytes);
|
||||||
const encodedBytes = Buffer.from(encodedBody, "utf8");
|
const encodedBytes = Buffer.from(encodedBody, "utf8");
|
||||||
|
|
||||||
const chatURL =
|
const chatURL = getQoderChatURL(providerMode);
|
||||||
"https://api3.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1";
|
|
||||||
|
|
||||||
const headers = buildAuthHeaders(encodedBytes, chatURL, {
|
const headers = buildAuthHeaders(encodedBytes, chatURL, {
|
||||||
userID,
|
userID,
|
||||||
|
|||||||
+13
-5
@@ -1,4 +1,5 @@
|
|||||||
import type { OAuthCredentials } from "@earendil-works/pi-ai";
|
import type { OAuthCredentials } from "@earendil-works/pi-ai";
|
||||||
|
import { getQoderManageUrl, getQoderMode, getQoderUsageURL, isQoderCNMode } from "./cosy.js";
|
||||||
|
|
||||||
interface QoderQuota {
|
interface QoderQuota {
|
||||||
total: number;
|
total: number;
|
||||||
@@ -32,9 +33,8 @@ export interface QoderProviderUsage {
|
|||||||
raw?: Record<string, unknown>;
|
raw?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function fetchQoderUsage(credentials: OAuthCredentials): Promise<QoderProviderUsage> {
|
async function fetchQoderUsageForMode(credentials: OAuthCredentials, mode: string): Promise<QoderProviderUsage> {
|
||||||
const usageURL = "https://openapi.qoder.sh/api/v2/quota/usage";
|
const response = await fetch(getQoderUsageURL(mode), {
|
||||||
const response = await fetch(usageURL, {
|
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${credentials.access}`,
|
Authorization: `Bearer ${credentials.access}`,
|
||||||
@@ -76,10 +76,18 @@ export async function fetchQoderUsage(credentials: OAuthCredentials): Promise<Qo
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
summary: remainingText,
|
summary: remainingText,
|
||||||
subscriptionTitle: "Qoder AI Plan",
|
subscriptionTitle: isQoderCNMode(mode) ? "Qoder CN Plan" : "Qoder AI Plan",
|
||||||
resetAt: raw.expiresAt ? new Date(raw.expiresAt).toISOString() : undefined,
|
resetAt: raw.expiresAt ? new Date(raw.expiresAt).toISOString() : undefined,
|
||||||
manageUrl: "https://qoder.com",
|
manageUrl: getQoderManageUrl(mode),
|
||||||
usageBuckets,
|
usageBuckets,
|
||||||
raw: raw as unknown as Record<string, unknown>,
|
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");
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user