diff --git a/package.json b/package.json index a0f4a39..6758a13 100644 --- a/package.json +++ b/package.json @@ -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 .", diff --git a/src/index.ts b/src/index.ts index f0478de..fa2d8d1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -36,10 +36,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[], _cred: OAuthCredentials) => { - const nonQoder = models.filter((m: Model) => 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, }; } diff --git a/src/oauth.ts b/src/oauth.ts index fca762b..675081c 100644 --- a/src/oauth.ts +++ b/src/oauth.ts @@ -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(); + +/** + * 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 { + 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 { + 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; } diff --git a/src/pat.ts b/src/pat.ts index 5ee7991..58f4a3d 100644 --- a/src/pat.ts +++ b/src/pat.ts @@ -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 = ""; diff --git a/src/stream.ts b/src/stream.ts index 371bd97..b99e276 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -20,8 +20,8 @@ import { getQoderUserEmailFallback, isQoderCNMode, } from "./cosy.js"; +import { resolveQoderIdentity, getCachedCredentials } from "./oauth.js"; import { getCachedModelConfig, MAX_OUTPUT_TOKENS } from "./models.js"; -import { getCachedCredentials } 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, 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(); // The model `id` pi exposes is the upstream display_name (whitespace // stripped) for CN, or the raw key for the international site. The @@ -137,7 +155,10 @@ export function streamQoder( const isReasoning = !!modelConfig.is_reasoning; 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--) { @@ -273,6 +294,7 @@ export function streamQoder( const modelSource = modelConfig.source || "system"; + const response = await fetch(chatURL, { method: "POST", headers: {