Merge pull request #8 from simonsmh/agent/auto-login-from-env
feat: auto-login from Qoder API key
This commit is contained in:
@@ -52,11 +52,14 @@ 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.
|
||||||
- Or set `QODER_PERSONAL_ACCESS_TOKEN` (or `QODER_PAT`) before starting pi.
|
- Or set `QODER_PERSONAL_ACCESS_TOKEN` (or `QODER_PAT`) before starting pi.
|
||||||
|
- `QODER_API_KEY` is also accepted; when set, pi automatically exchanges it
|
||||||
|
and logs the provider in during startup.
|
||||||
|
|
||||||
Qoder China:
|
Qoder China:
|
||||||
|
|
||||||
- Run `/login qoder-cn`, then paste the CN PAT.
|
- Run `/login qoder-cn`, then paste the CN PAT.
|
||||||
- Or set `QODERCN_PERSONAL_ACCESS_TOKEN` (or `QODERCN_PAT`) before starting pi.
|
- Or set `QODERCN_PERSONAL_ACCESS_TOKEN` (or `QODERCN_PAT`) before starting pi.
|
||||||
|
- `QODERCN_API_KEY` is also accepted and triggers the same automatic startup login.
|
||||||
|
|
||||||
> 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.
|
||||||
|
|||||||
+21
-2
@@ -8,7 +8,14 @@ import {
|
|||||||
toQoderCNFriendlyModel,
|
toQoderCNFriendlyModel,
|
||||||
} from "./cosy.js";
|
} from "./cosy.js";
|
||||||
import { getCachedModels, isCacheStale, staticCnModels, staticModels, updateQoderModelsCache } from "./models.js";
|
import { getCachedModels, isCacheStale, staticCnModels, staticModels, updateQoderModelsCache } from "./models.js";
|
||||||
import { getCachedCredentials, loginQoder, loginQoderCN, refreshQoderToken, refreshQoderTokenCN } from "./oauth.js";
|
import {
|
||||||
|
autoLoginQoderFromEnvironment,
|
||||||
|
getCachedCredentials,
|
||||||
|
loginQoder,
|
||||||
|
loginQoderCN,
|
||||||
|
refreshQoderToken,
|
||||||
|
refreshQoderTokenCN,
|
||||||
|
} from "./oauth.js";
|
||||||
import { streamQoder } from "./stream.js";
|
import { streamQoder } from "./stream.js";
|
||||||
import { fetchQoderUsage, fetchQoderUsageCN } from "./usage.js";
|
import { fetchQoderUsage, fetchQoderUsageCN } from "./usage.js";
|
||||||
|
|
||||||
@@ -57,7 +64,19 @@ function registerQoderProvider(pi: ExtensionAPI, providerID: string, mode: strin
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function (pi: ExtensionAPI) {
|
export default async function (pi: ExtensionAPI) {
|
||||||
|
for (const [providerID, mode] of [
|
||||||
|
["qoder", getQoderMode()],
|
||||||
|
["qoder-cn", "cn"],
|
||||||
|
] as const) {
|
||||||
|
try {
|
||||||
|
await autoLoginQoderFromEnvironment(providerID, mode);
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
console.error(`[pi-provider-qoder] Automatic login failed for ${providerID}: ${message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 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
|
||||||
|
|||||||
+23
-2
@@ -19,7 +19,7 @@ export interface QoderModelEntry {
|
|||||||
display_name?: string;
|
display_name?: string;
|
||||||
max_input_tokens?: number;
|
max_input_tokens?: number;
|
||||||
max_output_tokens?: number;
|
max_output_tokens?: number;
|
||||||
context_config?: Record<string, { token_count?: number }>;
|
context_config?: Record<string, { token_count?: number; is_default?: boolean }>;
|
||||||
is_vl?: boolean;
|
is_vl?: boolean;
|
||||||
is_reasoning?: boolean;
|
is_reasoning?: boolean;
|
||||||
thinking_config?: { enabled?: { efforts?: unknown } };
|
thinking_config?: { enabled?: { efforts?: unknown } };
|
||||||
@@ -358,7 +358,7 @@ export function getCachedModelConfig(modelKey: string, mode?: string): QoderMode
|
|||||||
try {
|
try {
|
||||||
const data = JSON.parse(readFileSync(cachePath, "utf8"));
|
const data = JSON.parse(readFileSync(cachePath, "utf8"));
|
||||||
if (data?.configs?.[modelKey]) {
|
if (data?.configs?.[modelKey]) {
|
||||||
return data.configs[modelKey] as QoderModelEntry;
|
return withMaxContextAsDefault(data.configs[modelKey] as QoderModelEntry);
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
@@ -394,6 +394,27 @@ export function getCachedModelConfig(modelKey: string, mode?: string): QoderMode
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Prefer the largest context option when Qoder exposes selectable contexts. */
|
||||||
|
function withMaxContextAsDefault(entry: QoderModelEntry): QoderModelEntry {
|
||||||
|
const contextConfig = entry.context_config;
|
||||||
|
if (!contextConfig || typeof contextConfig !== "object") return entry;
|
||||||
|
|
||||||
|
const maxTokenCount = Math.max(
|
||||||
|
...Object.values(contextConfig).map((config) => (typeof config?.token_count === "number" ? config.token_count : 0)),
|
||||||
|
);
|
||||||
|
if (maxTokenCount <= 0) return entry;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...entry,
|
||||||
|
context_config: Object.fromEntries(
|
||||||
|
Object.entries(contextConfig).map(([name, config]) => [
|
||||||
|
name,
|
||||||
|
{ ...config, is_default: config.token_count === maxTokenCount },
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function isCacheStale(mode?: string): boolean {
|
export function isCacheStale(mode?: string): boolean {
|
||||||
const cachePath = getQoderCachePath(mode);
|
const cachePath = getQoderCachePath(mode);
|
||||||
if (!existsSync(cachePath)) return true;
|
if (!existsSync(cachePath)) return true;
|
||||||
|
|||||||
+25
-2
@@ -2,7 +2,8 @@ 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, getQoderCNPat, getQoderMode, getQoderRefreshURL, isQoderCNMode } from "./cosy.js";
|
import { AuthStorage } from "@earendil-works/pi-coding-agent";
|
||||||
|
import { getMachineId, 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";
|
||||||
@@ -16,6 +17,28 @@ export interface QoderCredentials extends OAuthCredentials {
|
|||||||
|
|
||||||
const AUTH_FILE = join(homedir(), ".pi", "agent", "auth.json");
|
const AUTH_FILE = join(homedir(), ".pi", "agent", "auth.json");
|
||||||
|
|
||||||
|
/** Return the PAT exposed through the environment for a provider mode. */
|
||||||
|
export function getQoderPatForMode(mode: string): string {
|
||||||
|
if (isQoderCNMode(mode)) {
|
||||||
|
return process.env.QODERCN_API_KEY || process.env.QODERCN_PERSONAL_ACCESS_TOKEN || process.env.QODERCN_PAT || "";
|
||||||
|
}
|
||||||
|
return process.env.QODER_API_KEY || process.env.QODER_PERSONAL_ACCESS_TOKEN || process.env.QODER_PAT || "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exchange an environment PAT before pi resolves its initial model. */
|
||||||
|
export async function autoLoginQoderFromEnvironment(providerID: string, mode: string): Promise<void> {
|
||||||
|
const pat = getQoderPatForMode(mode);
|
||||||
|
if (!pat) return;
|
||||||
|
|
||||||
|
const authStorage = AuthStorage.create();
|
||||||
|
if (authStorage.get(providerID)) return;
|
||||||
|
|
||||||
|
const credentials = await credentialsFromPat(pat, mode);
|
||||||
|
authStorage.set(providerID, { type: "oauth", ...credentials });
|
||||||
|
const qCreds = credentials as QoderCredentials;
|
||||||
|
updateQoderModelsCache(qCreds.access, qCreds.userID, qCreds.name, qCreds.email, mode).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read the Qoder identity (userID/email/name/machineID) from pi's own auth
|
* Read the Qoder identity (userID/email/name/machineID) from pi's own auth
|
||||||
* store. pi persists the full OAuthCredentials there on login/refresh and keeps
|
* store. pi persists the full OAuthCredentials there on login/refresh and keeps
|
||||||
@@ -41,7 +64,7 @@ async function loginQoderForMode(callbacks: OAuthLoginCallbacks, mode: string):
|
|||||||
// 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 = isQoderCNMode(mode) ? getQoderCNPat() : process.env.QODER_PERSONAL_ACCESS_TOKEN || process.env.QODER_PAT;
|
const pat = getQoderPatForMode(mode);
|
||||||
if (pat) {
|
if (pat) {
|
||||||
try {
|
try {
|
||||||
const creds = await credentialsFromPat(pat, mode);
|
const creds = await credentialsFromPat(pat, mode);
|
||||||
|
|||||||
Reference in New Issue
Block a user