feat: init pi-provider-qoder plugin with oauth, signature and WAF bypass
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
*.log
|
||||
.DS_Store
|
||||
@@ -0,0 +1,85 @@
|
||||
# pi-provider-qoder
|
||||
|
||||
A [pi](https://shittycodingagent.ai/) provider extension that connects pi to the **Qoder API**, exposing Qoder models through one provider surface.
|
||||
|
||||
## Features
|
||||
|
||||
- **Interactive Login**: Standard OAuth browser device-code flow or Personal Access Token (PAT) login.
|
||||
- **WAF Bypass**: Built-in WAF obfuscation and body encoding (`Encode=1`).
|
||||
- **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.
|
||||
- **Reasoning/Thinking Support**: Real-time extraction of thinking process from API reasoning or HTML-like `<think>` tags.
|
||||
|
||||
## Quick start
|
||||
|
||||
Install the provider:
|
||||
|
||||
```bash
|
||||
pi install npm:pi-provider-qoder
|
||||
```
|
||||
|
||||
Or install it globally with npm:
|
||||
|
||||
```bash
|
||||
npm install -g pi-provider-qoder
|
||||
```
|
||||
|
||||
Then log in from pi:
|
||||
|
||||
```text
|
||||
/login qoder
|
||||
```
|
||||
|
||||
The login flow will prompt you to complete authorization in your browser.
|
||||
|
||||
### Personal Access Token (PAT) Fallback
|
||||
|
||||
For non-interactive environments, you can set the `QODER_PERSONAL_ACCESS_TOKEN` (or `QODER_PAT`) environment variable before starting pi. The provider will automatically pick up the PAT and authenticate.
|
||||
|
||||
## Models
|
||||
|
||||
Exposes the following backing models:
|
||||
|
||||
- **Tier Tiers**: `auto`, `ultimate`, `performance`, `efficient`, `lite`
|
||||
- **Frontier Models**:
|
||||
- `qmodel` (Qwen3.7 Plus)
|
||||
- `qmodel_latest` (Qwen3.7 Max)
|
||||
- `dmodel` (DeepSeek V4 Pro)
|
||||
- `dfmodel` (DeepSeek V4 Flash)
|
||||
- `gm51model` (GLM 5.1)
|
||||
- `kmodel` (Kimi K2.6)
|
||||
- `mmodel` (MiniMax M3)
|
||||
|
||||
## Usage
|
||||
|
||||
Once logged in, select any Qoder model in pi:
|
||||
|
||||
```text
|
||||
/model ultimate
|
||||
```
|
||||
|
||||
Or let Qoder select automatically:
|
||||
|
||||
```text
|
||||
/model auto
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
src/
|
||||
├── index.ts # Extension registration
|
||||
├── cosy.ts # COSY Signature and Machine ID resolver
|
||||
├── login.ts # OAuth Device Flow login sequence
|
||||
├── login-ui.ts # Custom TUI components for login
|
||||
├── models.ts # Model definitions and Dynamic Config Cache
|
||||
├── oauth.ts # PAT / OAuth callback orchestrator
|
||||
├── stream.ts # Main streaming response handler
|
||||
├── transform.ts # Message conversions (OpenAI schema mapping)
|
||||
├── thinking-parser.ts # Fallback <think> tag parser
|
||||
└── qoder-encoding.ts # WAF bypass body encoder
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/2.4.2/schema.json",
|
||||
"files": {
|
||||
"includes": ["src/**", "test/**", "*.ts", "*.json"]
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
"indentStyle": "space",
|
||||
"indentWidth": 2,
|
||||
"lineWidth": 120
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"nursery": {
|
||||
"recommended": true,
|
||||
"noNestedPromises": "off"
|
||||
}
|
||||
}
|
||||
},
|
||||
"assist": {
|
||||
"enabled": true
|
||||
},
|
||||
"json": {
|
||||
"formatter": {
|
||||
"trailingCommas": "none"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+4045
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "pi-provider-qoder",
|
||||
"version": "0.1.0",
|
||||
"description": "Pi extension for Qoder AI — with OAuth authentication, COSY signatures and WAF bypass",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"keywords": [
|
||||
"pi-package",
|
||||
"pi",
|
||||
"qoder",
|
||||
"ai",
|
||||
"provider"
|
||||
],
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "./node_modules/esbuild/bin/esbuild src/index.ts --bundle --platform=node --format=esm --outfile=dist/index.js --external:@earendil-works/pi-ai --external:@earendil-works/pi-coding-agent --external:@earendil-works/pi-tui",
|
||||
"check": "node node_modules/typescript/bin/tsc --noEmit",
|
||||
"lint": "node node_modules/@biomejs/biome/bin/biome check .",
|
||||
"lint:fix": "node node_modules/@biomejs/biome/bin/biome check --write .",
|
||||
"format": "node node_modules/@biomejs/biome/bin/biome format --write .",
|
||||
"prepare": "npm run build",
|
||||
"prepublishOnly": "npm run check && npm run build"
|
||||
},
|
||||
"pi": {
|
||||
"extensions": [
|
||||
"./dist/index.js"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"js-tiktoken": "^1.0.21"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.4.2",
|
||||
"@earendil-works/pi-ai": "^0.75.5",
|
||||
"@earendil-works/pi-coding-agent": "^0.75.5",
|
||||
"@earendil-works/pi-tui": "^0.75.5",
|
||||
"typescript": "^5.7.0"
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
import crypto from "node:crypto";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
const qoderRSAPublicKey = `-----BEGIN PUBLIC KEY-----
|
||||
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
|
||||
4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
|
||||
6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
|
||||
XcW+ML9FoCI6AOvOzwIDAQAB
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
const QoderIDEVersion = "1.0.0";
|
||||
const QoderClientType = "5";
|
||||
const QoderDataPolicy = "disagree";
|
||||
const QoderLoginVersion = "v2";
|
||||
const QoderMachineOS = "x86_64_windows";
|
||||
const QoderMachineTypeMagic = "5";
|
||||
|
||||
interface UserInfo {
|
||||
uid: string;
|
||||
security_oauth_token: string;
|
||||
name: string;
|
||||
aid: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface CosyPayload {
|
||||
version: string;
|
||||
requestId: string;
|
||||
info: string;
|
||||
cosyVersion: string;
|
||||
ideVersion: string;
|
||||
}
|
||||
|
||||
export interface CosyCredentials {
|
||||
userID: string;
|
||||
authToken: string;
|
||||
name: string;
|
||||
email: string;
|
||||
machineID?: string;
|
||||
}
|
||||
|
||||
function rsaEncryptBase64(data: Buffer | string): string {
|
||||
const key = {
|
||||
key: qoderRSAPublicKey,
|
||||
padding: crypto.constants.RSA_PKCS1_PADDING,
|
||||
};
|
||||
const encrypted = crypto.publicEncrypt(key, typeof data === "string" ? Buffer.from(data) : data);
|
||||
return encrypted.toString("base64");
|
||||
}
|
||||
|
||||
function aesEncryptCBCBase64(plaintext: string, keyStr: string): string {
|
||||
const cipher = crypto.createCipheriv("aes-128-cbc", Buffer.from(keyStr), Buffer.from(keyStr));
|
||||
let encrypted = cipher.update(plaintext, "utf8", "base64");
|
||||
encrypted += cipher.final("base64");
|
||||
return encrypted;
|
||||
}
|
||||
|
||||
function computeSigPath(urlStr: string): string {
|
||||
const parsed = new URL(urlStr);
|
||||
let sigPath = parsed.pathname;
|
||||
if (sigPath.startsWith("/algo")) {
|
||||
sigPath = sigPath.substring("/algo".length);
|
||||
}
|
||||
return sigPath;
|
||||
}
|
||||
|
||||
export function getMachineId(): string {
|
||||
const paths = [join(homedir(), ".qoder", ".auth", "machine_id"), join(homedir(), ".pi", "agent", "qoder-machine-id")];
|
||||
for (const p of paths) {
|
||||
if (existsSync(p)) {
|
||||
try {
|
||||
const val = readFileSync(p, "utf8").trim();
|
||||
if (val) return val;
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
const newId = crypto.randomUUID();
|
||||
try {
|
||||
const savePath = paths[1];
|
||||
mkdirSync(dirname(savePath), { recursive: true });
|
||||
writeFileSync(savePath, newId, "utf8");
|
||||
} catch {}
|
||||
return newId;
|
||||
}
|
||||
|
||||
export function buildAuthHeaders(
|
||||
body: Buffer | string | null,
|
||||
requestURL: string,
|
||||
creds: CosyCredentials,
|
||||
): Record<string, string> {
|
||||
if (!creds.userID) {
|
||||
throw new Error("cosy: user id is empty");
|
||||
}
|
||||
if (!creds.authToken) {
|
||||
throw new Error("cosy: auth token is empty");
|
||||
}
|
||||
|
||||
const aesKey = crypto.randomUUID().replace(/-/g, "").slice(0, 16);
|
||||
const userInfo: UserInfo = {
|
||||
uid: creds.userID,
|
||||
security_oauth_token: creds.authToken,
|
||||
name: creds.name || "",
|
||||
aid: "",
|
||||
email: creds.email || "",
|
||||
};
|
||||
|
||||
const infoB64 = aesEncryptCBCBase64(JSON.stringify(userInfo), aesKey);
|
||||
const cosyKey = rsaEncryptBase64(aesKey);
|
||||
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString();
|
||||
const requestId = crypto.randomUUID();
|
||||
|
||||
const cosyPayload: CosyPayload = {
|
||||
version: "v1",
|
||||
requestId,
|
||||
info: infoB64,
|
||||
cosyVersion: QoderIDEVersion,
|
||||
ideVersion: "",
|
||||
};
|
||||
|
||||
const payloadB64 = Buffer.from(JSON.stringify(cosyPayload)).toString("base64");
|
||||
const sigPath = computeSigPath(requestURL);
|
||||
|
||||
const bodyStr = body ? (Buffer.isBuffer(body) ? body.toString("utf8") : body) : "";
|
||||
const sigInput = `${payloadB64}\n${cosyKey}\n${timestamp}\n${bodyStr}\n${sigPath}`;
|
||||
const sig = crypto.createHash("md5").update(sigInput).digest("hex");
|
||||
|
||||
const bodyHash = crypto
|
||||
.createHash("md5")
|
||||
.update(body || "")
|
||||
.digest("hex");
|
||||
const bodyLen = body ? (Buffer.isBuffer(body) ? body.length : Buffer.from(body).length).toString() : "0";
|
||||
|
||||
const machineID = creds.machineID || getMachineId();
|
||||
|
||||
return {
|
||||
Authorization: `Bearer COSY.${payloadB64}.${sig}`,
|
||||
"Cosy-Key": cosyKey,
|
||||
"Cosy-User": creds.userID,
|
||||
"Cosy-Date": timestamp,
|
||||
"Cosy-Version": QoderIDEVersion,
|
||||
"Cosy-Machineid": machineID,
|
||||
"Cosy-Machinetoken": machineID,
|
||||
"Cosy-Machinetype": QoderMachineTypeMagic,
|
||||
"Cosy-Machineos": QoderMachineOS,
|
||||
"Cosy-Clienttype": QoderClientType,
|
||||
"Cosy-Clientip": "127.0.0.1",
|
||||
"Cosy-Bodyhash": bodyHash,
|
||||
"Cosy-Bodylength": bodyLen,
|
||||
"Cosy-Sigpath": sigPath,
|
||||
"Cosy-Data-Policy": QoderDataPolicy,
|
||||
"Cosy-Organization-Id": "",
|
||||
"Cosy-Organization-Tags": "",
|
||||
"Login-Version": QoderLoginVersion,
|
||||
"X-Request-Id": crypto.randomUUID(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Api, Model, OAuthCredentials } from "@earendil-works/pi-ai";
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
import { setExtensionContext } from "./login-ui.js";
|
||||
import { getCachedModels, staticModels } from "./models.js";
|
||||
import { loginQoder, refreshQoderToken } from "./oauth.js";
|
||||
import { streamQoder } from "./stream.js";
|
||||
import { fetchQoderUsage } from "./usage.js";
|
||||
|
||||
export default function (pi: ExtensionAPI) {
|
||||
// Capture ctx for custom TUI login components
|
||||
pi.on("session_start", async (_event, ctx) => {
|
||||
setExtensionContext(ctx);
|
||||
});
|
||||
|
||||
pi.registerProvider("qoder", {
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
api: "qoder-api" as any,
|
||||
models: getCachedModels(),
|
||||
oauth: {
|
||||
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: Model<Api>) => ({
|
||||
...m,
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
}));
|
||||
|
||||
return [...nonQoder, ...modifiedQoder];
|
||||
},
|
||||
fetchUsage: fetchQoderUsage,
|
||||
} as any,
|
||||
streamSimple: streamQoder,
|
||||
});
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
||||
import { DynamicBorder, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
||||
import { Container, type SelectItem, SelectList, Text } from "@earendil-works/pi-tui";
|
||||
|
||||
export type LoginChoice = { method: "web" } | null; // cancelled
|
||||
|
||||
let _ctx: ExtensionContext | undefined;
|
||||
|
||||
export function setExtensionContext(ctx: ExtensionContext) {
|
||||
_ctx = ctx;
|
||||
}
|
||||
|
||||
export function hasExtensionContext(): boolean {
|
||||
return _ctx !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the login selection UI using pi's native TUI components.
|
||||
* Returns the user's choice or null if cancelled.
|
||||
*/
|
||||
export async function showLoginUI(): Promise<LoginChoice> {
|
||||
if (!_ctx) return null;
|
||||
const ctx = _ctx;
|
||||
|
||||
return ctx.ui.custom<LoginChoice>((tui, theme, _kb, done) => {
|
||||
const mainItems: SelectItem[] = [
|
||||
{ value: "web", label: "Browser Login", description: "Sign in via browser (OAuth device flow)" },
|
||||
];
|
||||
|
||||
const container = new Container();
|
||||
const border = new DynamicBorder((s: string) => theme.fg("accent", s));
|
||||
const title = new Text(theme.fg("accent", theme.bold("Qoder Login")), 1, 0);
|
||||
const hint = new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel"), 1, 0);
|
||||
const borderBottom = new DynamicBorder((s: string) => theme.fg("accent", s));
|
||||
|
||||
const selectList = new SelectList(mainItems, mainItems.length, {
|
||||
selectedPrefix: (t: string) => theme.fg("accent", t),
|
||||
selectedText: (t: string) => theme.fg("accent", t),
|
||||
description: (t: string) => theme.fg("muted", t),
|
||||
scrollInfo: (t: string) => theme.fg("dim", t),
|
||||
noMatch: (t: string) => theme.fg("warning", t),
|
||||
});
|
||||
|
||||
selectList.onSelect = (item) => {
|
||||
done({ method: item.value as "web" });
|
||||
};
|
||||
selectList.onCancel = () => done(null);
|
||||
|
||||
container.addChild(border);
|
||||
container.addChild(title);
|
||||
container.addChild(selectList);
|
||||
container.addChild(hint);
|
||||
container.addChild(borderBottom);
|
||||
|
||||
tui.requestRender();
|
||||
|
||||
return {
|
||||
render(width: number) {
|
||||
return container.render(width);
|
||||
},
|
||||
invalidate() {
|
||||
container.invalidate();
|
||||
},
|
||||
handleInput(data: string) {
|
||||
selectList.handleInput(data);
|
||||
tui.requestRender();
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a waiting UI wrapper with an Escape return loop logic.
|
||||
* The user can press Escape or 'q' to abort the current login flow immediately.
|
||||
*/
|
||||
export async function showWaitingUI(
|
||||
outerCallbacks: OAuthLoginCallbacks,
|
||||
runAuth: (mergedCallbacks: OAuthLoginCallbacks) => Promise<OAuthCredentials>,
|
||||
): Promise<OAuthCredentials | null> {
|
||||
if (!_ctx) {
|
||||
return runAuth(outerCallbacks);
|
||||
}
|
||||
const ctx = _ctx;
|
||||
|
||||
return ctx.ui.custom<OAuthCredentials | null>((tui, theme, _kb, done) => {
|
||||
const container = new Container();
|
||||
const border = new DynamicBorder((s: string) => theme.fg("accent", s));
|
||||
const title = new Text(theme.fg("accent", theme.bold("Qoder Login - Authorization")), 1, 0);
|
||||
const borderBottom = new DynamicBorder((s: string) => theme.fg("accent", s));
|
||||
|
||||
const statusText = new Text("Initiating login flow...", 1, 0);
|
||||
const urlText = new Text("", 1, 0);
|
||||
const instructionsText = new Text("", 1, 0);
|
||||
const hint = new Text(theme.fg("dim", "esc cancel / back"), 1, 0);
|
||||
|
||||
container.addChild(border);
|
||||
container.addChild(title);
|
||||
container.addChild(statusText);
|
||||
container.addChild(urlText);
|
||||
container.addChild(instructionsText);
|
||||
container.addChild(hint);
|
||||
container.addChild(borderBottom);
|
||||
|
||||
const abortCtrl = new AbortController();
|
||||
let onAuthCalled = false;
|
||||
|
||||
const mergedCallbacks: OAuthLoginCallbacks = {
|
||||
...outerCallbacks,
|
||||
onProgress: (msg: string) => {
|
||||
outerCallbacks.onProgress?.(msg);
|
||||
statusText.setText(msg);
|
||||
tui.requestRender();
|
||||
},
|
||||
onAuth: (info: { url: string; instructions?: string }) => {
|
||||
if (!onAuthCalled) {
|
||||
onAuthCalled = true;
|
||||
outerCallbacks.onAuth?.(info);
|
||||
}
|
||||
urlText.setText(`URL: ${info.url}`);
|
||||
instructionsText.setText(info.instructions || "");
|
||||
tui.requestRender();
|
||||
},
|
||||
signal: abortCtrl.signal,
|
||||
};
|
||||
|
||||
runAuth(mergedCallbacks).then(
|
||||
(creds) => {
|
||||
done(creds);
|
||||
},
|
||||
(err) => {
|
||||
if (abortCtrl.signal.aborted) {
|
||||
done(null);
|
||||
} else {
|
||||
statusText.setText(theme.fg("warning", `Error: ${err.message || err}`));
|
||||
tui.requestRender();
|
||||
setTimeout(() => done(null), 3000);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
render(width: number) {
|
||||
return container.render(width);
|
||||
},
|
||||
invalidate() {
|
||||
container.invalidate();
|
||||
},
|
||||
handleInput(data: string) {
|
||||
// Escape key (standalone 0x1B) or 'q' to cancel
|
||||
if ((data.length === 1 && data.charCodeAt(0) === 0x1b) || data === "q") {
|
||||
abortCtrl.abort();
|
||||
done(null);
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
||||
import { getMachineId } from "./cosy.js";
|
||||
import { hasExtensionContext, showLoginUI, showWaitingUI } from "./login-ui.js";
|
||||
|
||||
type PromptFn = (p: { message: string; placeholder?: string; allowEmpty?: boolean }) => Promise<string>;
|
||||
|
||||
function getPrompt(callbacks: OAuthLoginCallbacks): PromptFn {
|
||||
return (callbacks as unknown as { onPrompt: PromptFn }).onPrompt;
|
||||
}
|
||||
|
||||
function getProgress(callbacks: OAuthLoginCallbacks): ((msg: string) => void) | undefined {
|
||||
return (callbacks as unknown as { onProgress?: (msg: string) => void }).onProgress;
|
||||
}
|
||||
|
||||
function getSignal(callbacks: OAuthLoginCallbacks): AbortSignal | undefined {
|
||||
return (callbacks as unknown as { signal?: AbortSignal }).signal;
|
||||
}
|
||||
|
||||
export function generatePKCE() {
|
||||
const codeVerifier = crypto.randomBytes(32).toString("base64url");
|
||||
const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
|
||||
return { codeVerifier, codeChallenge };
|
||||
}
|
||||
|
||||
function parseExpiresAt(s?: string, expiresInSeconds?: number): number {
|
||||
if (s) {
|
||||
const t = Date.parse(s);
|
||||
if (!Number.isNaN(t)) return t;
|
||||
const ms = Number.parseInt(s, 10);
|
||||
if (!Number.isNaN(ms) && ms > 0) return ms;
|
||||
}
|
||||
if (expiresInSeconds && expiresInSeconds > 0) {
|
||||
return Date.now() + expiresInSeconds * 1000;
|
||||
}
|
||||
return Date.now() + 30 * 24 * 60 * 60 * 1000; // default 30 days
|
||||
}
|
||||
|
||||
export async function interactiveLogin(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
||||
if (hasExtensionContext()) {
|
||||
const choice = await showLoginUI();
|
||||
if (!choice) {
|
||||
throw new Error("Login cancelled");
|
||||
}
|
||||
|
||||
const runAuth = async (mergedCallbacks: OAuthLoginCallbacks) => {
|
||||
return runDeviceFlow(mergedCallbacks);
|
||||
};
|
||||
|
||||
const creds = await showWaitingUI(callbacks, runAuth);
|
||||
if (!creds) {
|
||||
throw new Error("Login cancelled");
|
||||
}
|
||||
return creds;
|
||||
}
|
||||
|
||||
// Fallback for terminal prompt
|
||||
const prompt = getPrompt(callbacks);
|
||||
const proceed = await prompt({
|
||||
message: "Press Enter to start browser login for Qoder",
|
||||
placeholder: "press enter",
|
||||
allowEmpty: true,
|
||||
});
|
||||
|
||||
if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled");
|
||||
return runDeviceFlow(callbacks);
|
||||
}
|
||||
|
||||
function abortableDelay(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
if (signal?.aborted) return Promise.reject(signal.reason || new Error("Login cancelled"));
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(signal?.reason || new Error("Login cancelled"));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function runDeviceFlow(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
||||
const { codeVerifier, codeChallenge } = generatePKCE();
|
||||
const nonce = crypto.randomUUID();
|
||||
const machineID = getMachineId();
|
||||
|
||||
const verificationURI = `https://qoder.com/device/selectAccounts?challenge=${codeChallenge}&challenge_method=S256&machine_id=${machineID}&nonce=${nonce}`;
|
||||
|
||||
getProgress(callbacks)?.("Please complete login in your browser...");
|
||||
|
||||
(callbacks as unknown as { onAuth: (info: { url: string; instructions: string }) => void }).onAuth({
|
||||
url: verificationURI,
|
||||
instructions: "Click to sign in with your Qoder account in the browser.",
|
||||
});
|
||||
|
||||
const pollURL = `https://openapi.qoder.sh/api/v1/deviceToken/poll?nonce=${encodeURIComponent(nonce)}&verifier=${encodeURIComponent(codeVerifier)}&challenge_method=S256`;
|
||||
const pollInterval = 2000;
|
||||
const maxAttempts = 90; // 3 minutes
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (getSignal(callbacks)?.aborted) throw new Error("Login cancelled");
|
||||
await abortableDelay(pollInterval, getSignal(callbacks));
|
||||
|
||||
try {
|
||||
const response = await fetch(pollURL, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "pi-provider-qoder",
|
||||
},
|
||||
signal: getSignal(callbacks),
|
||||
});
|
||||
|
||||
if (response.status === 202 || response.status === 404) {
|
||||
// Pending
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text();
|
||||
throw new Error(`Device token poll failed: ${response.status} ${response.statusText}. Response: ${errText}`);
|
||||
}
|
||||
|
||||
const tokenData = (await response.json()) as {
|
||||
token: string;
|
||||
user_id: string;
|
||||
refresh_token: string;
|
||||
expires_at?: string;
|
||||
expires_in?: number;
|
||||
};
|
||||
|
||||
if (!tokenData.token) {
|
||||
throw new Error("Device token poll returned empty access token");
|
||||
}
|
||||
|
||||
const expireMs = parseExpiresAt(tokenData.expires_at, tokenData.expires_in);
|
||||
|
||||
// Fetch user info (best effort)
|
||||
getProgress(callbacks)?.("Fetching user profile...");
|
||||
let email = "";
|
||||
let name = "";
|
||||
try {
|
||||
const userinfoRes = await fetch("https://openapi.qoder.sh/api/v1/userinfo", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${tokenData.token}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": "pi-provider-qoder",
|
||||
},
|
||||
});
|
||||
if (userinfoRes.ok) {
|
||||
const userinfo = (await userinfoRes.json()) as {
|
||||
email?: string;
|
||||
name?: string;
|
||||
username?: string;
|
||||
};
|
||||
email = userinfo.email || "";
|
||||
name = userinfo.name || userinfo.username || "";
|
||||
}
|
||||
} catch {}
|
||||
|
||||
getProgress(callbacks)?.("Login successful!");
|
||||
|
||||
return {
|
||||
refresh: `${tokenData.refresh_token}|${tokenData.user_id}|${machineID}`,
|
||||
access: tokenData.token,
|
||||
expires: expireMs - 5 * 60 * 1000, // 5 min buffer
|
||||
userID: tokenData.user_id,
|
||||
email,
|
||||
name,
|
||||
machineID,
|
||||
} as any;
|
||||
} catch (e: any) {
|
||||
if (e.name === "AbortError" || getSignal(callbacks)?.aborted) {
|
||||
throw new Error("Login cancelled");
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Authorization timed out");
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
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");
|
||||
|
||||
export const ZERO_COST = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
||||
|
||||
export interface QoderModelDef {
|
||||
id: string;
|
||||
name: string;
|
||||
api: "qoder-api";
|
||||
provider: "qoder";
|
||||
baseUrl: string;
|
||||
reasoning: boolean;
|
||||
supportsEffort: boolean;
|
||||
input: ("text" | "image")[];
|
||||
cost: typeof ZERO_COST;
|
||||
contextWindow: number;
|
||||
maxTokens: number;
|
||||
}
|
||||
|
||||
export const staticModels: QoderModelDef[] = [
|
||||
{
|
||||
id: "auto",
|
||||
name: "Qoder Auto",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: true,
|
||||
supportsEffort: false,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "ultimate",
|
||||
name: "Qoder Ultimate",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: true,
|
||||
supportsEffort: true,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "performance",
|
||||
name: "Qoder Performance",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: true,
|
||||
supportsEffort: true,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 272000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "efficient",
|
||||
name: "Qoder Efficient",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: false,
|
||||
supportsEffort: false,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "lite",
|
||||
name: "Qoder Lite",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: false,
|
||||
supportsEffort: false,
|
||||
input: ["text"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "qmodel",
|
||||
name: "Qwen3.7 Plus (Qoder)",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: false,
|
||||
supportsEffort: false,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "qmodel_latest",
|
||||
name: "Qwen3.7 Max (Qoder)",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: false,
|
||||
supportsEffort: false,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "dmodel",
|
||||
name: "DeepSeek V4 Pro (Qoder)",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: true,
|
||||
supportsEffort: true,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "dfmodel",
|
||||
name: "DeepSeek V4 Flash (Qoder)",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: true,
|
||||
supportsEffort: true,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "gm51model",
|
||||
name: "GLM 5.1 (Qoder)",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: true,
|
||||
supportsEffort: true,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "kmodel",
|
||||
name: "Kimi K2.6 (Qoder)",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: false,
|
||||
supportsEffort: false,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 256000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "mmodel",
|
||||
name: "MiniMax M3 (Qoder)",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: false,
|
||||
supportsEffort: false,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
];
|
||||
|
||||
export function getCachedModels(): QoderModelDef[] {
|
||||
if (existsSync(CACHE_PATH)) {
|
||||
try {
|
||||
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
|
||||
if (data && Array.isArray(data.models)) {
|
||||
return data.models;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
return staticModels;
|
||||
}
|
||||
|
||||
export function getCachedModelConfig(modelKey: string): Record<string, any> | null {
|
||||
if (existsSync(CACHE_PATH)) {
|
||||
try {
|
||||
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
|
||||
if (data && data.configs && data.configs[modelKey]) {
|
||||
return data.configs[modelKey];
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isCacheStale(): boolean {
|
||||
if (!existsSync(CACHE_PATH)) return true;
|
||||
try {
|
||||
const data = JSON.parse(readFileSync(CACHE_PATH, "utf8"));
|
||||
if (!data || typeof data.updatedAt !== "number") return true;
|
||||
// Stale if older than 1 hour
|
||||
return Date.now() - data.updatedAt > 3600_000;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateQoderModelsCache(
|
||||
authToken: string,
|
||||
userID: string,
|
||||
name: string,
|
||||
email: string,
|
||||
): Promise<void> {
|
||||
const modelListURL = "https://api3.qoder.sh/algo/api/v2/model/list";
|
||||
try {
|
||||
const headers = buildAuthHeaders(null, modelListURL, {
|
||||
userID,
|
||||
authToken,
|
||||
name,
|
||||
email,
|
||||
});
|
||||
|
||||
const response = await fetch(modelListURL, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
...headers,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resData = (await response.json()) as { chat?: any[] };
|
||||
const chatModels = resData.chat || [];
|
||||
if (chatModels.length === 0) return;
|
||||
|
||||
const newModels: QoderModelDef[] = [];
|
||||
const configs: Record<string, any> = {};
|
||||
|
||||
for (const entry of chatModels) {
|
||||
const key = entry.key;
|
||||
if (!key || !entry.enable) continue;
|
||||
|
||||
const display = entry.display_name || key;
|
||||
const ctxLen = entry.max_input_tokens || 180000;
|
||||
const isVL = !!entry.is_vl;
|
||||
const isReasoning = !!entry.is_reasoning || !!entry.thinking_config;
|
||||
const supportsEffort = !!entry.thinking_config?.enabled?.efforts;
|
||||
|
||||
configs[key] = entry;
|
||||
|
||||
newModels.push({
|
||||
id: key,
|
||||
name: display,
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: isReasoning,
|
||||
supportsEffort,
|
||||
input: isVL ? ["text", "image"] : ["text"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: ctxLen,
|
||||
maxTokens: entry.max_output_tokens || 32768,
|
||||
});
|
||||
}
|
||||
|
||||
if (newModels.length === 0) return;
|
||||
|
||||
// Ensure auto is present
|
||||
if (!newModels.some((m) => m.id === "auto")) {
|
||||
newModels.unshift({
|
||||
id: "auto",
|
||||
name: "Qoder Auto",
|
||||
api: "qoder-api",
|
||||
provider: "qoder",
|
||||
baseUrl: "https://api3.qoder.sh/",
|
||||
reasoning: true,
|
||||
supportsEffort: false,
|
||||
input: ["text", "image"],
|
||||
cost: ZERO_COST,
|
||||
contextWindow: 180000,
|
||||
maxTokens: 32768,
|
||||
});
|
||||
}
|
||||
|
||||
const cacheData = {
|
||||
updatedAt: Date.now(),
|
||||
models: newModels,
|
||||
configs,
|
||||
};
|
||||
|
||||
mkdirSync(dirname(CACHE_PATH), { recursive: true });
|
||||
writeFileSync(CACHE_PATH, JSON.stringify(cacheData, null, 2), "utf-8");
|
||||
} catch {}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
||||
import { getMachineId } from "./cosy.js";
|
||||
import { interactiveLogin } from "./login.js";
|
||||
import { updateQoderModelsCache } from "./models.js";
|
||||
|
||||
export interface QoderCredentials extends OAuthCredentials {
|
||||
userID: string;
|
||||
email: string;
|
||||
name: string;
|
||||
machineID: string;
|
||||
}
|
||||
|
||||
const CREDENTIALS_CACHE_FILE = join(homedir(), ".pi", "agent", "qoder-credentials-cache.json");
|
||||
|
||||
export function saveCachedCredentials(creds: QoderCredentials) {
|
||||
try {
|
||||
mkdirSync(dirname(CREDENTIALS_CACHE_FILE), { recursive: true });
|
||||
writeFileSync(CREDENTIALS_CACHE_FILE, JSON.stringify(creds, null, 2), "utf-8");
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function getCachedCredentials(accessToken: string): QoderCredentials | null {
|
||||
if (existsSync(CREDENTIALS_CACHE_FILE)) {
|
||||
try {
|
||||
const creds = JSON.parse(readFileSync(CREDENTIALS_CACHE_FILE, "utf-8"));
|
||||
if (creds && creds.access === accessToken) {
|
||||
return creds as QoderCredentials;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function loginQoder(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
||||
// 1. Try environment variables first (PAT)
|
||||
const pat = process.env.QODER_PERSONAL_ACCESS_TOKEN || process.env.QODER_PAT;
|
||||
if (pat) {
|
||||
try {
|
||||
const userinfoRes = await fetch("https://openapi.qoder.sh/api/v1/userinfo", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${pat}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": "pi-provider-qoder",
|
||||
},
|
||||
});
|
||||
if (userinfoRes.ok) {
|
||||
const userinfo = (await userinfoRes.json()) as {
|
||||
id?: string;
|
||||
email?: string;
|
||||
name?: string;
|
||||
username?: string;
|
||||
};
|
||||
const email = userinfo.email || "";
|
||||
const name = userinfo.name || userinfo.username || "";
|
||||
const userID = userinfo.id || "pat";
|
||||
const machineID = getMachineId();
|
||||
|
||||
const creds = {
|
||||
refresh: `pat|${userID}|${machineID}`,
|
||||
access: pat,
|
||||
expires: Date.now() + 30 * 24 * 60 * 60 * 1000, // 30 days
|
||||
userID,
|
||||
email,
|
||||
name,
|
||||
machineID,
|
||||
};
|
||||
|
||||
saveCachedCredentials(creds);
|
||||
// Cache models in background
|
||||
updateQoderModelsCache(pat, userID, name, email).catch(() => {});
|
||||
|
||||
return creds;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 2. Interactive login
|
||||
const creds = await interactiveLogin(callbacks);
|
||||
|
||||
// Cache models in background and save credentials
|
||||
try {
|
||||
const qCreds = creds as QoderCredentials;
|
||||
saveCachedCredentials(qCreds);
|
||||
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email).catch(() => {});
|
||||
} catch {}
|
||||
|
||||
return creds;
|
||||
}
|
||||
|
||||
export async function refreshQoderToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
|
||||
const parts = credentials.refresh.split("|");
|
||||
const refreshToken = parts[0] || "";
|
||||
const userID = parts[1] || "";
|
||||
const machineID = parts[2] || getMachineId();
|
||||
|
||||
if (refreshToken === "pat") {
|
||||
// PAT tokens don't need refreshing, just extend validity
|
||||
return {
|
||||
...credentials,
|
||||
expires: Date.now() + 30 * 24 * 60 * 60 * 1000,
|
||||
};
|
||||
}
|
||||
|
||||
const refreshURL = "https://center.qoder.sh/algo/api/v3/user/refresh_token";
|
||||
try {
|
||||
const response = await fetch(refreshURL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${credentials.access}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": "pi-provider-qoder",
|
||||
},
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = (await response.json()) as {
|
||||
token: string;
|
||||
refresh_token?: string;
|
||||
expires_at?: string;
|
||||
expires_in?: number;
|
||||
};
|
||||
|
||||
const newAccess = data.token;
|
||||
const newRefresh = data.refresh_token || refreshToken;
|
||||
|
||||
let expireMs = Date.now() + 30 * 24 * 60 * 60 * 1000;
|
||||
if (data.expires_at) {
|
||||
const parsed = Date.parse(data.expires_at);
|
||||
if (!Number.isNaN(parsed)) expireMs = parsed;
|
||||
} else if (data.expires_in) {
|
||||
expireMs = Date.now() + data.expires_in * 1000;
|
||||
}
|
||||
|
||||
const refreshed = {
|
||||
...credentials,
|
||||
refresh: `${newRefresh}|${userID}|${machineID}`,
|
||||
access: newAccess,
|
||||
expires: expireMs - 5 * 60 * 1000,
|
||||
userID,
|
||||
email: (credentials as any).email || "",
|
||||
name: (credentials as any).name || "",
|
||||
machineID,
|
||||
};
|
||||
|
||||
saveCachedCredentials(refreshed as QoderCredentials);
|
||||
// Cache models in background
|
||||
updateQoderModelsCache(
|
||||
newAccess,
|
||||
userID,
|
||||
(credentials as any).name || "",
|
||||
(credentials as any).email || "",
|
||||
).catch(() => {});
|
||||
|
||||
return refreshed;
|
||||
}
|
||||
} catch {}
|
||||
|
||||
// Fallback: Extend validity slightly to buy time, as Qoder tokens are long-lived
|
||||
const refreshedFallback = {
|
||||
...credentials,
|
||||
expires: Date.now() + 60 * 60 * 1000, // extend for 1 hour
|
||||
};
|
||||
try {
|
||||
saveCachedCredentials(refreshedFallback as QoderCredentials);
|
||||
} catch {}
|
||||
return refreshedFallback;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
const qoderCustomAlphabet = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!";
|
||||
const qoderStdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
export function qoderEncodeBody(plaintext: string | Buffer): string {
|
||||
const std = Buffer.isBuffer(plaintext) ? plaintext.toString("base64") : Buffer.from(plaintext).toString("base64");
|
||||
const n = std.length;
|
||||
const a = Math.floor(n / 3);
|
||||
const rearranged = std.slice(n - a) + std.slice(a, n - a) + std.slice(0, a);
|
||||
let out = "";
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = rearranged[i];
|
||||
if (c === "=") {
|
||||
out += "$";
|
||||
} else {
|
||||
const idx = qoderStdAlphabet.indexOf(c);
|
||||
if (idx >= 0) {
|
||||
out += qoderCustomAlphabet[idx];
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
import crypto from "node:crypto";
|
||||
import type {
|
||||
Api,
|
||||
AssistantMessage,
|
||||
AssistantMessageEventStream,
|
||||
Context,
|
||||
Model,
|
||||
SimpleStreamOptions,
|
||||
} from "@earendil-works/pi-ai";
|
||||
import * as PiAi from "@earendil-works/pi-ai";
|
||||
import { buildAuthHeaders, getMachineId } from "./cosy.js";
|
||||
import { getCachedModelConfig } from "./models.js";
|
||||
import { getCachedCredentials } from "./oauth.js";
|
||||
import { qoderEncodeBody } from "./qoder-encoding.js";
|
||||
import { ThinkingTagParser } from "./thinking-parser.js";
|
||||
import { transformMessagesForQoder, transformTools } from "./transform.js";
|
||||
|
||||
function stableHash(prefix: string, ...inputs: string[]): string {
|
||||
const hash = crypto.createHash("sha256");
|
||||
hash.update(prefix);
|
||||
for (const input of inputs) {
|
||||
hash.update("\0");
|
||||
hash.update(input);
|
||||
}
|
||||
return hash.digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
function stableChatRecordID(model: string, messages: any[], tools: any, maxTokens: number): string {
|
||||
const hash = crypto.createHash("sha256");
|
||||
hash.update("qoder-record");
|
||||
hash.update("\0");
|
||||
hash.update(model);
|
||||
for (const msg of messages) {
|
||||
if (msg && msg.role) {
|
||||
hash.update("\0");
|
||||
hash.update(msg.role);
|
||||
}
|
||||
if (msg && msg.content) {
|
||||
hash.update("\0");
|
||||
hash.update(typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content));
|
||||
}
|
||||
}
|
||||
if (tools) {
|
||||
hash.update("\0");
|
||||
hash.update(JSON.stringify(tools));
|
||||
}
|
||||
hash.update("\0");
|
||||
hash.update(`mt=${maxTokens}`);
|
||||
return hash.digest("hex").slice(0, 16);
|
||||
}
|
||||
|
||||
export function streamQoder(
|
||||
model: Model<Api>,
|
||||
context: Context,
|
||||
options?: SimpleStreamOptions,
|
||||
): AssistantMessageEventStream {
|
||||
const StreamCtor = (PiAi as unknown as { AssistantMessageEventStream: new () => AssistantMessageEventStream })
|
||||
.AssistantMessageEventStream;
|
||||
const stream = new StreamCtor();
|
||||
|
||||
const output: AssistantMessage = {
|
||||
role: "assistant",
|
||||
content: [],
|
||||
api: model.api,
|
||||
provider: model.provider,
|
||||
model: model.id,
|
||||
usage: {
|
||||
input: 0,
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
totalTokens: 0,
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
||||
},
|
||||
stopReason: "stop",
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const accessToken = options?.apiKey;
|
||||
if (!accessToken) {
|
||||
throw new Error("Qoder credentials not set. Run /login qoder or set QODER_PERSONAL_ACCESS_TOKEN.");
|
||||
}
|
||||
|
||||
// Resolve user details from cached credentials
|
||||
const cachedCreds = getCachedCredentials(accessToken);
|
||||
const userID = cachedCreds?.userID || "qoder-user";
|
||||
const name = cachedCreds?.name || "Qoder User";
|
||||
const email = cachedCreds?.email || "user@qoder.com";
|
||||
const machineID = cachedCreds?.machineID || getMachineId();
|
||||
|
||||
const qoderModel = model.id;
|
||||
const modelConfig = getCachedModelConfig(qoderModel) || {
|
||||
key: qoderModel,
|
||||
is_reasoning:
|
||||
qoderModel === "ultimate" ||
|
||||
qoderModel === "performance" ||
|
||||
qoderModel.includes("dmodel") ||
|
||||
qoderModel.includes("dfmodel"),
|
||||
max_output_tokens: 32768,
|
||||
source: "system",
|
||||
};
|
||||
modelConfig.key = qoderModel;
|
||||
|
||||
const isReasoning = !!modelConfig.is_reasoning;
|
||||
const maxOutputTokens = modelConfig.max_output_tokens || 32768;
|
||||
|
||||
const normalizedMessages = transformMessagesForQoder(context.messages);
|
||||
const systemText = context.systemPrompt || "";
|
||||
|
||||
let lastUserText = "";
|
||||
for (let i = normalizedMessages.length - 1; i >= 0; i--) {
|
||||
if (normalizedMessages[i].role === "user") {
|
||||
const content = normalizedMessages[i].content;
|
||||
lastUserText =
|
||||
typeof content === "string"
|
||||
? content
|
||||
: Array.isArray(content)
|
||||
? content.map((c) => c.text || "").join("")
|
||||
: "";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const sessionID = stableHash("qoder-session", userID, qoderModel);
|
||||
|
||||
let maxTokens = 32768;
|
||||
if (maxOutputTokens > 0) {
|
||||
maxTokens = maxOutputTokens;
|
||||
}
|
||||
if (options?.maxTokens && options.maxTokens < maxTokens) {
|
||||
maxTokens = options.maxTokens;
|
||||
}
|
||||
|
||||
const toolsRaw = context.tools && context.tools.length > 0 ? transformTools(context.tools) : undefined;
|
||||
const recordID = stableChatRecordID(qoderModel, normalizedMessages, toolsRaw, maxTokens);
|
||||
|
||||
const reqBody: Record<string, any> = {
|
||||
request_id: crypto.randomUUID(),
|
||||
request_set_id: recordID,
|
||||
chat_record_id: recordID,
|
||||
session_id: sessionID,
|
||||
stream: true,
|
||||
chat_task: "FREE_INPUT",
|
||||
is_reply: true,
|
||||
is_retry: false,
|
||||
source: 1,
|
||||
version: "3",
|
||||
session_type: "qodercli",
|
||||
agent_id: "agent_common",
|
||||
task_id: "common",
|
||||
code_language: "",
|
||||
chat_prompt: "",
|
||||
image_urls: null,
|
||||
aliyun_user_type: "",
|
||||
system: systemText,
|
||||
messages: normalizedMessages,
|
||||
tools: toolsRaw || [],
|
||||
parameters: { max_tokens: maxTokens },
|
||||
chat_context: {
|
||||
chatPrompt: "",
|
||||
imageUrls: null,
|
||||
extra: {
|
||||
context: [],
|
||||
modelConfig: {
|
||||
key: qoderModel,
|
||||
is_reasoning: isReasoning,
|
||||
},
|
||||
originalContent: lastUserText,
|
||||
},
|
||||
features: [],
|
||||
text: lastUserText,
|
||||
},
|
||||
model_config: modelConfig,
|
||||
business: {
|
||||
product: "cli",
|
||||
version: "1.0.0",
|
||||
type: "agent",
|
||||
stage: "start",
|
||||
id: crypto.randomUUID(),
|
||||
name: lastUserText.substring(0, 30),
|
||||
begin_at: Date.now(),
|
||||
},
|
||||
};
|
||||
|
||||
const bodyBytes = Buffer.from(JSON.stringify(reqBody));
|
||||
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 headers = buildAuthHeaders(encodedBytes, chatURL, {
|
||||
userID,
|
||||
authToken: accessToken,
|
||||
name,
|
||||
email,
|
||||
machineID,
|
||||
});
|
||||
|
||||
const modelSource = modelConfig.source || "system";
|
||||
|
||||
const response = await fetch(chatURL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Accept-Encoding": "identity",
|
||||
"X-Model-Key": qoderModel,
|
||||
"X-Model-Source": modelSource,
|
||||
...headers,
|
||||
},
|
||||
body: encodedBytes,
|
||||
signal: options?.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errText = await response.text();
|
||||
throw new Error(`Qoder API request failed: ${response.status} ${response.statusText}. Response: ${errText}`);
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error("No response body");
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
|
||||
let contentBlockIndex = -1;
|
||||
let thinkingBlockIndex = -1;
|
||||
const toolCallsState: any[] = [];
|
||||
|
||||
const thinkingEnabled = (options?.reasoning as any) !== false && (options?.reasoning as any) !== "off";
|
||||
const thinkingParser = thinkingEnabled ? new ThinkingTagParser(output, stream) : null;
|
||||
|
||||
stream.push({ type: "start", partial: output });
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
while (true) {
|
||||
const lineEnd = buffer.indexOf("\n");
|
||||
if (lineEnd === -1) break;
|
||||
|
||||
const line = buffer.substring(0, lineEnd).trim();
|
||||
buffer = buffer.substring(lineEnd + 1);
|
||||
|
||||
if (!line.startsWith("data:")) continue;
|
||||
|
||||
const dataStr = line.substring(5).trim();
|
||||
if (dataStr === "[DONE]") {
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
const envelope = JSON.parse(dataStr);
|
||||
if (envelope.statusCodeValue && envelope.statusCodeValue !== 200) {
|
||||
throw new Error(`Upstream status ${envelope.statusCodeValue}: ${envelope.body}`);
|
||||
}
|
||||
|
||||
const innerStr = envelope.body;
|
||||
if (!innerStr || innerStr === "[DONE]") continue;
|
||||
|
||||
const inner = JSON.parse(innerStr);
|
||||
if (inner.choices && inner.choices.length > 0) {
|
||||
const choice = inner.choices[0];
|
||||
const delta = choice.delta;
|
||||
|
||||
if (delta) {
|
||||
// 1. Process reasoning/thinking content (API reasoning)
|
||||
if (delta.reasoning_content) {
|
||||
if (thinkingBlockIndex === -1) {
|
||||
thinkingBlockIndex = output.content.length;
|
||||
output.content.push({ type: "thinking", thinking: "" } as any);
|
||||
stream.push({ type: "thinking_start", contentIndex: thinkingBlockIndex, partial: output });
|
||||
}
|
||||
const block = output.content[thinkingBlockIndex] as any;
|
||||
block.thinking += delta.reasoning_content;
|
||||
stream.push({
|
||||
type: "thinking_delta",
|
||||
contentIndex: thinkingBlockIndex,
|
||||
delta: delta.reasoning_content,
|
||||
partial: output,
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Process text content
|
||||
if (delta.content) {
|
||||
// End API thinking block if active
|
||||
if (thinkingBlockIndex !== -1) {
|
||||
const block = output.content[thinkingBlockIndex] as any;
|
||||
stream.push({
|
||||
type: "thinking_end",
|
||||
contentIndex: thinkingBlockIndex,
|
||||
content: block.thinking,
|
||||
partial: output,
|
||||
});
|
||||
thinkingBlockIndex = -1;
|
||||
}
|
||||
|
||||
if (thinkingParser) {
|
||||
thinkingParser.processChunk(delta.content);
|
||||
} else {
|
||||
if (contentBlockIndex === -1) {
|
||||
contentBlockIndex = output.content.length;
|
||||
output.content.push({ type: "text", text: "" } as any);
|
||||
stream.push({ type: "text_start", contentIndex: contentBlockIndex, partial: output });
|
||||
}
|
||||
const block = output.content[contentBlockIndex] as any;
|
||||
block.text += delta.content;
|
||||
stream.push({
|
||||
type: "text_delta",
|
||||
contentIndex: contentBlockIndex,
|
||||
delta: delta.content,
|
||||
partial: output,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Process tool calls
|
||||
if (delta.tool_calls && Array.isArray(delta.tool_calls)) {
|
||||
for (const tc of delta.tool_calls) {
|
||||
const idx = tc.index ?? 0;
|
||||
if (!toolCallsState[idx]) {
|
||||
toolCallsState[idx] = { arguments: "" };
|
||||
}
|
||||
const state = toolCallsState[idx];
|
||||
if (tc.id) state.id = tc.id;
|
||||
if (tc.function?.name) state.name = tc.function.name;
|
||||
if (tc.function?.arguments) {
|
||||
const argDelta = tc.function.arguments;
|
||||
state.arguments += argDelta;
|
||||
|
||||
if (state.emittedStart === undefined) {
|
||||
state.emittedStart = true;
|
||||
state.contentIndex = output.content.length;
|
||||
const block = { type: "toolCall", id: state.id, name: state.name, arguments: {} };
|
||||
output.content.push(block as any);
|
||||
stream.push({ type: "toolcall_start", contentIndex: state.contentIndex, partial: output });
|
||||
}
|
||||
stream.push({
|
||||
type: "toolcall_delta",
|
||||
contentIndex: state.contentIndex,
|
||||
delta: argDelta,
|
||||
partial: output,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (choice.finish_reason) {
|
||||
output.stopReason = choice.finish_reason;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
if (thinkingParser) {
|
||||
thinkingParser.finalize();
|
||||
}
|
||||
|
||||
if (thinkingBlockIndex !== -1) {
|
||||
const block = output.content[thinkingBlockIndex] as any;
|
||||
stream.push({
|
||||
type: "thinking_end",
|
||||
contentIndex: thinkingBlockIndex,
|
||||
content: block.thinking,
|
||||
partial: output,
|
||||
});
|
||||
}
|
||||
|
||||
for (const state of toolCallsState) {
|
||||
if (state && state.emittedStart && !state.emittedEnd) {
|
||||
state.emittedEnd = true;
|
||||
let args = {};
|
||||
try {
|
||||
args = JSON.parse(state.arguments || "{}");
|
||||
} catch {}
|
||||
const block = output.content[state.contentIndex] as any;
|
||||
block.arguments = args;
|
||||
stream.push({
|
||||
type: "toolcall_end",
|
||||
contentIndex: state.contentIndex,
|
||||
toolCall: {
|
||||
type: "toolCall",
|
||||
id: state.id,
|
||||
name: state.name,
|
||||
arguments: args,
|
||||
},
|
||||
partial: output,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (toolCallsState.length > 0) {
|
||||
output.stopReason = "toolUse";
|
||||
} else {
|
||||
output.stopReason = "stop";
|
||||
}
|
||||
stream.push({ type: "done", reason: output.stopReason as "stop" | "toolUse", message: output });
|
||||
stream.end();
|
||||
} catch (e: any) {
|
||||
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
||||
output.errorMessage = e instanceof Error ? e.message : String(e);
|
||||
stream.push({ type: "error", reason: output.stopReason, error: output });
|
||||
try {
|
||||
stream.end();
|
||||
} catch {}
|
||||
}
|
||||
})();
|
||||
|
||||
return stream;
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import type {
|
||||
AssistantMessage,
|
||||
AssistantMessageEventStream,
|
||||
TextContent,
|
||||
ThinkingContent,
|
||||
} from "@earendil-works/pi-ai";
|
||||
|
||||
export const THINKING_START_TAG = "<thinking>";
|
||||
export const THINKING_END_TAG = "</thinking>";
|
||||
|
||||
const THINKING_TAG_VARIANTS: Array<{ open: string; close: string }> = [
|
||||
{ open: "<thinking>", close: "</thinking>" },
|
||||
{ open: "<think>", close: "</think>" },
|
||||
{ open: "<reasoning>", close: "</reasoning>" },
|
||||
{ open: "<thought>", close: "</thought>" },
|
||||
];
|
||||
|
||||
function getTrailingPossibleTagPrefixLength(text: string, tag: string): number {
|
||||
const maxPrefixLength = Math.min(text.length, tag.length - 1);
|
||||
for (let len = maxPrefixLength; len > 0; len--) {
|
||||
if (text.endsWith(tag.slice(0, len))) return len;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function getMaxTrailingPossibleTagPrefixLength(text: string, tags: string[]): number {
|
||||
let maxLength = 0;
|
||||
for (const tag of tags) {
|
||||
maxLength = Math.max(maxLength, getTrailingPossibleTagPrefixLength(text, tag));
|
||||
}
|
||||
return maxLength;
|
||||
}
|
||||
|
||||
export class ThinkingTagParser {
|
||||
private textBuffer = "";
|
||||
private inThinking = false;
|
||||
private thinkingExtracted = false;
|
||||
private thinkingBlockIndex: number | null = null;
|
||||
private textBlockIndex: number | null = null;
|
||||
private lastTextBlockIndex: number | null = null;
|
||||
private activeEndTag: string = THINKING_END_TAG;
|
||||
|
||||
constructor(
|
||||
private output: AssistantMessage,
|
||||
private stream: AssistantMessageEventStream,
|
||||
) {}
|
||||
|
||||
processChunk(chunk: string): void {
|
||||
this.textBuffer += chunk;
|
||||
while (this.textBuffer.length > 0) {
|
||||
const prevLength = this.textBuffer.length;
|
||||
if (!this.inThinking && !this.thinkingExtracted) {
|
||||
this.processBeforeThinking();
|
||||
if (this.textBuffer.length === 0) break;
|
||||
}
|
||||
if (this.inThinking) {
|
||||
this.processInsideThinking();
|
||||
if (this.textBuffer.length === 0) break;
|
||||
}
|
||||
if (this.thinkingExtracted) {
|
||||
this.processAfterThinking();
|
||||
break;
|
||||
}
|
||||
if (this.textBuffer.length >= prevLength) break;
|
||||
}
|
||||
}
|
||||
|
||||
finalize(): void {
|
||||
if (this.textBuffer.length === 0) return;
|
||||
if (this.inThinking && this.thinkingBlockIndex !== null) {
|
||||
const block = this.output.content[this.thinkingBlockIndex] as ThinkingContent;
|
||||
block.thinking += this.textBuffer;
|
||||
this.stream.push({
|
||||
type: "thinking_delta",
|
||||
contentIndex: this.thinkingBlockIndex,
|
||||
delta: this.textBuffer,
|
||||
partial: this.output,
|
||||
});
|
||||
this.stream.push({
|
||||
type: "thinking_end",
|
||||
contentIndex: this.thinkingBlockIndex,
|
||||
content: block.thinking,
|
||||
partial: this.output,
|
||||
});
|
||||
} else {
|
||||
this.emitText(this.textBuffer);
|
||||
}
|
||||
this.textBuffer = "";
|
||||
}
|
||||
|
||||
getTextBlockIndex(): number | null {
|
||||
return this.textBlockIndex ?? this.lastTextBlockIndex;
|
||||
}
|
||||
|
||||
private processBeforeThinking(): void {
|
||||
let bestPos = -1;
|
||||
let bestVariant: (typeof THINKING_TAG_VARIANTS)[number] | null = null;
|
||||
for (const variant of THINKING_TAG_VARIANTS) {
|
||||
const pos = this.textBuffer.indexOf(variant.open);
|
||||
if (pos !== -1 && (bestPos === -1 || pos < bestPos)) {
|
||||
bestPos = pos;
|
||||
bestVariant = variant;
|
||||
}
|
||||
}
|
||||
if (bestPos !== -1 && bestVariant) {
|
||||
if (bestPos > 0) this.emitText(this.textBuffer.slice(0, bestPos));
|
||||
this.textBuffer = this.textBuffer.slice(bestPos + bestVariant.open.length);
|
||||
this.activeEndTag = bestVariant.close;
|
||||
this.inThinking = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const trailingPrefixLength = getMaxTrailingPossibleTagPrefixLength(
|
||||
this.textBuffer,
|
||||
THINKING_TAG_VARIANTS.map((variant) => variant.open),
|
||||
);
|
||||
const safeLen = this.textBuffer.length - trailingPrefixLength;
|
||||
if (safeLen > 0) {
|
||||
this.emitText(this.textBuffer.slice(0, safeLen));
|
||||
this.textBuffer = this.textBuffer.slice(safeLen);
|
||||
}
|
||||
}
|
||||
|
||||
private processInsideThinking(): void {
|
||||
const endPos = this.textBuffer.indexOf(this.activeEndTag);
|
||||
if (endPos !== -1) {
|
||||
if (endPos > 0) this.emitThinking(this.textBuffer.slice(0, endPos));
|
||||
if (this.thinkingBlockIndex !== null) {
|
||||
const block = this.output.content[this.thinkingBlockIndex] as ThinkingContent;
|
||||
this.stream.push({
|
||||
type: "thinking_end",
|
||||
contentIndex: this.thinkingBlockIndex,
|
||||
content: block.thinking,
|
||||
partial: this.output,
|
||||
});
|
||||
}
|
||||
this.textBuffer = this.textBuffer.slice(endPos + this.activeEndTag.length);
|
||||
this.inThinking = false;
|
||||
this.thinkingExtracted = true;
|
||||
this.lastTextBlockIndex = this.textBlockIndex;
|
||||
this.textBlockIndex = null;
|
||||
if (this.textBuffer.startsWith("\n\n")) this.textBuffer = this.textBuffer.slice(2);
|
||||
return;
|
||||
}
|
||||
|
||||
const trailingPrefixLength = getTrailingPossibleTagPrefixLength(this.textBuffer, this.activeEndTag);
|
||||
const safeLen = this.textBuffer.length - trailingPrefixLength;
|
||||
if (safeLen > 0) {
|
||||
this.emitThinking(this.textBuffer.slice(0, safeLen));
|
||||
this.textBuffer = this.textBuffer.slice(safeLen);
|
||||
}
|
||||
}
|
||||
|
||||
private processAfterThinking(): void {
|
||||
this.emitText(this.textBuffer);
|
||||
this.textBuffer = "";
|
||||
}
|
||||
|
||||
private emitText(text: string): void {
|
||||
if (!text) return;
|
||||
if (this.textBlockIndex === null) {
|
||||
this.textBlockIndex = this.output.content.length;
|
||||
this.output.content.push({ type: "text", text: "" });
|
||||
this.stream.push({ type: "text_start", contentIndex: this.textBlockIndex, partial: this.output });
|
||||
}
|
||||
const block = this.output.content[this.textBlockIndex] as TextContent;
|
||||
block.text += text;
|
||||
this.stream.push({ type: "text_delta", contentIndex: this.textBlockIndex, delta: text, partial: this.output });
|
||||
}
|
||||
|
||||
private emitThinking(thinking: string): void {
|
||||
if (!thinking) return;
|
||||
if (this.thinkingBlockIndex === null) {
|
||||
if (this.textBlockIndex !== null) {
|
||||
this.thinkingBlockIndex = this.textBlockIndex;
|
||||
this.output.content.splice(this.thinkingBlockIndex, 0, { type: "thinking", thinking: "" });
|
||||
this.textBlockIndex = this.textBlockIndex + 1;
|
||||
} else {
|
||||
this.thinkingBlockIndex = this.output.content.length;
|
||||
this.output.content.push({ type: "thinking", thinking: "" });
|
||||
}
|
||||
this.stream.push({ type: "thinking_start", contentIndex: this.thinkingBlockIndex, partial: this.output });
|
||||
}
|
||||
const block = this.output.content[this.thinkingBlockIndex] as ThinkingContent;
|
||||
block.thinking += thinking;
|
||||
this.stream.push({
|
||||
type: "thinking_delta",
|
||||
contentIndex: this.thinkingBlockIndex,
|
||||
delta: thinking,
|
||||
partial: this.output,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import type {
|
||||
AssistantMessage,
|
||||
ImageContent,
|
||||
Message,
|
||||
TextContent,
|
||||
ThinkingContent,
|
||||
Tool,
|
||||
ToolCall,
|
||||
ToolResultMessage,
|
||||
} from "@earendil-works/pi-ai";
|
||||
|
||||
export function getContentText(msg: Message): string {
|
||||
if (typeof msg.content === "string") return msg.content;
|
||||
if (Array.isArray(msg.content)) {
|
||||
return msg.content
|
||||
.map((c) => {
|
||||
if (c.type === "text") return (c as TextContent).text;
|
||||
if (c.type === "thinking") return (c as ThinkingContent).thinking;
|
||||
return "";
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function transformTools(tools: Tool[]): any[] {
|
||||
return tools.map((t) => ({
|
||||
type: "function",
|
||||
function: {
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
parameters: t.parameters,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function transformMessagesForQoder(messages: Message[]): any[] {
|
||||
const normalizedMessages: any[] = [];
|
||||
|
||||
for (const msg of messages) {
|
||||
// Skip error or aborted messages
|
||||
if (
|
||||
msg.role === "assistant" &&
|
||||
((msg as AssistantMessage).stopReason === "error" || (msg as AssistantMessage).stopReason === "aborted")
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (msg.role === "user") {
|
||||
let content: any = "";
|
||||
if (typeof msg.content === "string") {
|
||||
content = msg.content;
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
const hasImage = msg.content.some((c) => c.type === "image");
|
||||
if (hasImage) {
|
||||
content = msg.content
|
||||
.map((c) => {
|
||||
if (c.type === "text") {
|
||||
return { type: "text", text: (c as TextContent).text };
|
||||
}
|
||||
if (c.type === "image") {
|
||||
const img = c as ImageContent;
|
||||
return {
|
||||
type: "image_url",
|
||||
image_url: {
|
||||
url: `data:${img.mimeType};base64,${img.data}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean);
|
||||
} else {
|
||||
content = getContentText(msg);
|
||||
}
|
||||
}
|
||||
normalizedMessages.push({
|
||||
role: "user",
|
||||
content,
|
||||
});
|
||||
} else if (msg.role === "assistant") {
|
||||
const am = msg as AssistantMessage;
|
||||
let content = "";
|
||||
const toolCalls: any[] = [];
|
||||
|
||||
if (Array.isArray(am.content)) {
|
||||
for (const block of am.content) {
|
||||
if (block.type === "text") {
|
||||
content += (block as TextContent).text;
|
||||
} else if (block.type === "thinking") {
|
||||
// Include thinking tags if reasoning is on
|
||||
content += `<thinking>${(block as ThinkingContent).thinking}</thinking>\n\n`;
|
||||
} else if (block.type === "toolCall") {
|
||||
const tc = block as ToolCall;
|
||||
toolCalls.push({
|
||||
id: tc.id,
|
||||
type: "function",
|
||||
function: {
|
||||
name: tc.name,
|
||||
arguments: typeof tc.arguments === "string" ? tc.arguments : JSON.stringify(tc.arguments),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
content = am.content || "";
|
||||
}
|
||||
|
||||
const mapped: any = {
|
||||
role: "assistant",
|
||||
content: content || null,
|
||||
};
|
||||
if (toolCalls.length > 0) {
|
||||
mapped.tool_calls = toolCalls;
|
||||
}
|
||||
normalizedMessages.push(mapped);
|
||||
} else if (msg.role === "toolResult") {
|
||||
const tr = msg as ToolResultMessage;
|
||||
normalizedMessages.push({
|
||||
role: "tool",
|
||||
tool_call_id: tr.toolCallId,
|
||||
content: getContentText(tr),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return normalizedMessages;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { OAuthCredentials } from "@earendil-works/pi-ai";
|
||||
|
||||
interface QoderQuota {
|
||||
total: number;
|
||||
used: number;
|
||||
remaining: number;
|
||||
percentage: number;
|
||||
unit: string;
|
||||
}
|
||||
|
||||
interface QoderUsageInfo {
|
||||
userQuota: QoderQuota;
|
||||
orgResourcePackage: QoderQuota;
|
||||
totalUsagePercentage: number;
|
||||
isQuotaExceeded: boolean;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export interface QoderProviderUsage {
|
||||
summary?: string;
|
||||
subscriptionTitle?: string;
|
||||
resetAt?: string;
|
||||
manageUrl?: string;
|
||||
usageBuckets?: Array<{
|
||||
id: string;
|
||||
label: string;
|
||||
usedDisplay: string;
|
||||
limitDisplay?: string;
|
||||
unit?: string;
|
||||
resetAt?: string;
|
||||
}>;
|
||||
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, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${credentials.access}`,
|
||||
Accept: "application/json",
|
||||
"User-Agent": "pi-provider-qoder",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch Qoder usage: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const raw = (await response.json()) as QoderUsageInfo;
|
||||
const usageBuckets = [];
|
||||
|
||||
if (raw.userQuota) {
|
||||
usageBuckets.push({
|
||||
id: "user-quota",
|
||||
label: "User Quota",
|
||||
usedDisplay: raw.userQuota.used.toFixed(2),
|
||||
limitDisplay: raw.userQuota.total.toFixed(2),
|
||||
unit: raw.userQuota.unit,
|
||||
resetAt: raw.expiresAt ? new Date(raw.expiresAt).toISOString() : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
if (raw.orgResourcePackage && raw.orgResourcePackage.total > 0) {
|
||||
usageBuckets.push({
|
||||
id: "org-resource-package",
|
||||
label: "Org Resource Package",
|
||||
usedDisplay: raw.orgResourcePackage.used.toFixed(2),
|
||||
limitDisplay: raw.orgResourcePackage.total.toFixed(2),
|
||||
unit: raw.orgResourcePackage.unit,
|
||||
resetAt: raw.expiresAt ? new Date(raw.expiresAt).toISOString() : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
const remainingText = raw.userQuota ? `${raw.userQuota.remaining.toFixed(2)} ${raw.userQuota.unit} remaining` : "";
|
||||
|
||||
return {
|
||||
summary: remainingText,
|
||||
subscriptionTitle: "Qoder AI Plan",
|
||||
resetAt: raw.expiresAt ? new Date(raw.expiresAt).toISOString() : undefined,
|
||||
manageUrl: "https://qoder.com",
|
||||
usageBuckets,
|
||||
raw: raw as unknown as Record<string, unknown>,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "dist",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "dist", "test"]
|
||||
}
|
||||
Reference in New Issue
Block a user