fix: qoder-cn chat identity, content normalization, and Windows build

- Resolve the real Qoder identity (userID/email/name/machineID) from the
  job token at request time. OMP keeps login credentials in its own
  agent.db, not in ~/.pi/agent/auth.json, so a cache miss sent uid
  "qoder-user" and Qoder CN rejected it with "Login expired" (105).
- Normalize the system prompt to a plain string. OMP supplies it as a
  single-element content array which Qoder's MessagesInputDto#content
  (String) rejects with 400 "Execution failed: set property" on qwen models.
- Drop the modifyModels hook. OMP (Bun) structuredClones the whole model
  catalog before invoking it, and its bundled catalog is not cloneable,
  which removed qoder from `omp models`.
- Make the build script cross-platform: use esbuild on PATH instead of a
  Unix-style ./node_modules path that fails on Windows cmd.exe.
This commit is contained in:
xing.huang
2026-08-18 12:22:47 +08:00
parent 9820845768
commit 443e4ad6a7
5 changed files with 87 additions and 18 deletions
+1 -1
View File
@@ -19,7 +19,7 @@
"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",
"build": "esbuild src/index.ts --bundle --platform=node --format=esm --outfile=dist/index.js --external:@earendil-works/pi-ai --external:@earendil-works/pi-coding-agent",
"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 .",
+5 -4
View File
@@ -45,10 +45,11 @@ function createQoderOAuth(providerID: string, mode: string): OAuthConfigWithUsag
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)];
},
// NOTE: no `modifyModels` hook on purpose. OMP (Bun) does a whole-catalog
// structuredClone before invoking it, and its bundled catalog contains a
// model with a non-cloneable property -> "The object can not be cloned."
// removes qoder from `omp models`. Models are supplied at registration
// via `modelsForProvider` and refreshed by the startup/session cache hooks.
fetchUsage: isQoderCNMode(mode) ? fetchQoderUsageCN : fetchQoderUsage,
};
}
+50 -4
View File
@@ -3,10 +3,10 @@ import { homedir } from "node:os";
import { dirname, join } from "node:path";
import type { OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
import { AuthStorage } from "@earendil-works/pi-coding-agent";
import { getMachineId, getQoderMode, getQoderRefreshURL, isQoderCNMode } from "./cosy.js";
import { getMachineId, getQoderMode, getQoderRefreshURL, getQoderUserEmailFallback, isQoderCNMode } from "./cosy.js";
import { interactiveLogin } from "./login.js";
import { updateQoderModelsCache } from "./models.js";
import { credentialsFromPat, decodePatRefresh, isPatRefresh } from "./pat.js";
import { credentialsFromPat, decodePatRefresh, fetchUserInfo, isPatRefresh } from "./pat.js";
export interface QoderCredentials extends OAuthCredentials {
userID: string;
@@ -93,7 +93,46 @@ export function getCachedCredentials(_accessToken: string, providerID = "qoder")
return null;
}
const identityCache = new Map<string, QoderCredentials>();
/**
* Resolve the Qoder identity (userID/email/name/machineID) for a chat request.
* OMP (17.x) persists login credentials in its own agent.db, not in
* ~/.pi/agent/auth.json, so the provider-side cache is frequently empty and the
* COSY payload would fall back to uid "qoder-user" -> Qoder CN rejects it with
* "Login expired" (105). Fetch the identity from the job token when the cache
* misses (in-memory cached), and persist it so later requests skip the fetch.
*/
export async function resolveQoderIdentity(
accessToken: string,
providerID: string,
mode: string,
): Promise<QoderCredentials> {
const cached = getCachedCredentials(accessToken, providerID);
if (cached?.userID) return cached;
const cacheKey = `${providerID}:${accessToken}`;
const mem = identityCache.get(cacheKey);
if (mem?.userID) return mem;
const info = await fetchUserInfo(accessToken, mode);
const machineID = getMachineId();
const creds: QoderCredentials = {
access: accessToken,
userID: info.userID || "qoder-user",
email: info.email || getQoderUserEmailFallback(mode),
name: info.name || (isQoderCNMode(mode) ? "Qoder CN User" : "Qoder User"),
machineID,
refresh: "",
expires: 0,
};
identityCache.set(cacheKey, creds);
saveCredentialsToAuthFile(providerID, creds);
return creds;
}
async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: string): Promise<OAuthCredentials> {
const providerID = isQoderCNMode(mode) ? "qoder-cn" : "qoder";
// 1. Try environment variables first (PAT). A PAT (pt-...) must be exchanged
// for a short-lived job token before it can be used — credentialsFromPat
// handles the exchange + identity resolution.
@@ -102,9 +141,14 @@ async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: string):
try {
const creds = await credentialsFromPat(pat, mode);
const qCreds = creds as QoderCredentials;
// pi persists these credentials in auth.json itself; no separate cache needed.
// Persist the resolved identity locally so chat requests can resolve the real uid.
// Cache models in background
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode).catch(() => {});
// Persist the resolved identity locally. OMP (17.x) stores login
// credentials in its own agent.db, not in ~/.pi/agent/auth.json, so
// without this the chat COSY payload would fall back to uid "qoder-user"
// and Qoder CN rejects it with "Login expired" (105).
saveCredentialsToAuthFile(providerID, creds);
return creds;
} catch {
// Fall through to interactive login if PAT exchange fails.
@@ -114,12 +158,14 @@ async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: string):
// 2. Interactive login (CN only supports PAT prompt here; global supports device flow fallback)
const creds = await interactiveLogin(callbacks, mode);
// Cache models in background. pi persists the credentials in auth.json itself.
// Cache models in background.
try {
const qCreds = creds as QoderCredentials;
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode).catch(() => {});
} catch {}
// Persist the resolved identity locally (see note above).
saveCredentialsToAuthFile(providerID, creds);
return creds;
}
+1 -1
View File
@@ -102,7 +102,7 @@ export async function exchangeJobToken(pat: string, mode: string = getQoderMode(
}
/** Fetch user profile using a job token (jt-...). Best-effort. */
async function fetchUserInfo(jobToken: string, mode: string): Promise<{ userID: string; email: string; name: string }> {
export async function fetchUserInfo(jobToken: string, mode: string): Promise<{ userID: string; email: string; name: string }> {
let userID = "";
let email = "";
let name = "";
+30 -8
View File
@@ -21,7 +21,7 @@ import {
isQoderCNMode,
} from "./cosy.js";
import { getCachedModelConfig } from "./models.js";
import { getCachedCredentials } from "./oauth.js";
import { resolveQoderIdentity } from "./oauth.js";
import { qoderEncodeBody } from "./qoder-encoding.js";
import { stripThinkingTags, ThinkingTagParser } from "./thinking-parser.js";
import { transformMessagesForQoder, transformTools } from "./transform.js";
@@ -74,6 +74,21 @@ function stableChatRecordID(
return hash.digest("hex").slice(0, 16);
}
function contentToText(content: unknown): string {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
return content
.map((part) => {
if (typeof part === "string") return part;
if (part && typeof part === "object" && "text" in part) return (part as { text: string }).text;
return "";
})
.join("\n");
}
return "";
}
export function streamQoder(
model: Model<Api>,
context: Context,
@@ -113,12 +128,15 @@ export function streamQoder(
);
}
// Resolve user details from cached credentials
const cachedCreds = getCachedCredentials(accessToken, model.provider);
const userID = cachedCreds?.userID || "qoder-user";
const name = cachedCreds?.name || (isQoderCNMode(providerMode) ? "Qoder CN User" : "Qoder User");
const email = cachedCreds?.email || getQoderUserEmailFallback(providerMode);
const machineID = cachedCreds?.machineID || getMachineId();
// Resolve the real Qoder identity from the job token. OMP keeps login
// credentials in its own agent.db, not in ~/.pi/agent/auth.json, so a
// cache miss would otherwise send uid "qoder-user" and Qoder CN rejects
// it with "Login expired" (105).
const ident = await resolveQoderIdentity(accessToken, model.provider, providerMode);
const userID = ident.userID || "qoder-user";
const name = ident.name || (isQoderCNMode(providerMode) ? "Qoder CN User" : "Qoder User");
const email = ident.email || getQoderUserEmailFallback(providerMode);
const machineID = ident.machineID || getMachineId();
const qoderModel = isQoderCNMode(providerMode) ? getQoderCNDirectModel(model.id) : model.id;
const modelConfig = getCachedModelConfig(qoderModel, providerMode) || {
@@ -137,7 +155,10 @@ export function streamQoder(
const maxOutputTokens = modelConfig.max_output_tokens || 32768;
const normalizedMessages = transformMessagesForQoder(context.messages);
const systemText = context.systemPrompt || "";
// OMP may supply the system prompt as a single-element content array;
// Qoder MessagesInputDto#content is a String and rejects an array with
// "Execution failed: set property ... MessagesInputDto#content". Normalize.
const systemText = contentToText(context.systemPrompt || "");
let lastUserText = "";
for (let i = normalizedMessages.length - 1; i >= 0; i--) {
@@ -239,6 +260,7 @@ export function streamQoder(
const modelSource = modelConfig.source || "system";
const response = await fetch(chatURL, {
method: "POST",
headers: {