Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions plugin/lib/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ const translations = {
zaiApiError: (status: number, text: string) =>
`Z.ai API 请求失败 (${status}): ${text}`,
zhipuTokensLimit: "5 小时 Token 限额",
zhipuCreditLimit: "5 小时积分限额",
zhipuWeeklyLimit: "每周 Token 限额",
zhipuMcpLimit: "MCP 月度配额",
zhipuAccountName: "Coding Plan",
zaiAccountName: "Z.ai",
Expand Down Expand Up @@ -163,6 +165,8 @@ const translations = {
zaiApiError: (status: number, text: string) =>
`Z.ai API request failed (${status}): ${text}`,
zhipuTokensLimit: "5-hour token limit",
zhipuCreditLimit: "5-hour credit limit",
zhipuWeeklyLimit: "Weekly token limit",
zhipuMcpLimit: "MCP monthly quota",
zhipuAccountName: "Coding Plan",
zaiAccountName: "Z.ai",
Expand Down
214 changes: 211 additions & 3 deletions plugin/lib/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,15 @@
* [同步]: mystatus.ts, types.ts, utils.ts, i18n.ts
*/

import { homedir } from "os";
import { readFile, writeFile, rename, chmod } from "fs/promises";
import { join } from "path";
import { t } from "./i18n";
import { type QueryResult, type OpenAIAuthData } from "./types";
import {
type AuthData,
type QueryResult,
type OpenAIAuthData,
} from "./types";
import {
formatDuration,
createProgressBar,
Expand All @@ -35,6 +42,32 @@ interface OpenAIUsageResponse {
} | null;
}

/** OAuth token 刷新响应(refresh token 已轮换,新值必须持久化) */
interface TokenResponse {
access_token: string;
refresh_token: string;
/** 新的 id token(优先用于提取账号 ID) */
id_token?: string;
/** access token 有效期(秒) */
expires_in?: number;
}

/** auth.json 中的 openai 条目(含刷新时可能回填的 accountId) */
type OpenAIAuthEntry = OpenAIAuthData & { accountId?: string };

/**
* 携带 HTTP 状态码的错误(供调用方识别 401 触发 token 刷新)
*/
class HttpError extends Error {
readonly status: number;

constructor(message: string, status: number) {
super(message);
this.name = "HttpError";
this.status = status;
}
}

// ============================================================================
// JWT 解析
// ============================================================================
Expand All @@ -46,6 +79,8 @@ interface JwtPayload {
"https://api.openai.com/auth"?: {
chatgpt_account_id?: string;
};
chatgpt_account_id?: string;
organizations?: Array<{ id?: string }>;
}

/**
Expand Down Expand Up @@ -88,6 +123,23 @@ function getAccountIdFromJwt(token: string): string | null {
return payload?.["https://api.openai.com/auth"]?.chatgpt_account_id ?? null;
}

/**
* 从 JWT claims 中解析 ChatGPT 账号 ID
* 优先级:chatgpt_account_id → auth 命名空间 → organizations[0].id
*/
function extractAccountIdFromClaims(token: string): string | null {
const payload = parseJwt(token);
if (!payload) {
return null;
}
return (
payload.chatgpt_account_id ??
payload["https://api.openai.com/auth"]?.chatgpt_account_id ??
payload.organizations?.[0]?.id ??
null
);
}

// ============================================================================
// 工具函数
// ============================================================================
Expand Down Expand Up @@ -148,12 +200,126 @@ async function fetchOpenAIUsage(

if (!response.ok) {
const errorText = await response.text();
throw new Error(t.apiError(response.status, errorText));
// 附加状态码,供调用方识别 401 触发 token 刷新
const error = new HttpError(
t.apiError(response.status, errorText),
response.status,
);
throw error;
}

return response.json() as Promise<OpenAIUsageResponse>;
}

// ============================================================================
// OAuth token 刷新(对齐 OpenCode 官方刷新契约)
// ============================================================================

const OPENAI_TOKEN_URL = "https://auth.openai.com/oauth/token";
const OPENAI_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
const OPENAI_AUTH_PATH = join(homedir(), ".local/share/opencode/auth.json");

/**
* 使用 refresh token 换取新的 access token
* 注意:refresh token 每次刷新都会轮换,新值必须持久化
* @throws 带 HTTP 状态码与响应体的错误
*/
async function refreshOpenAIToken(
refreshToken: string,
): Promise<TokenResponse> {
const body = new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
client_id: OPENAI_OAUTH_CLIENT_ID,
});

const response = await fetchWithTimeout(OPENAI_TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: body.toString(),
});

if (!response.ok) {
const errorText = await response.text();
throw new Error(t.apiError(response.status, errorText));
}

return response.json() as Promise<TokenResponse>;
}

/**
* 判断错误是否为 "文件不存在"(ENOENT)
*/
function isEnoentError(err: unknown): boolean {
return (
err instanceof Error && (err as NodeJS.ErrnoException).code === "ENOENT"
);
}

/**
* 原子合并写入 auth.json 的 openai 条目(保留其他 provider 条目)
* 先写同目录临时文件(mode 0600)再 rename,避免半写状态
*/
async function persistOpenAIAuth(
authPath: string,
updatedEntry: OpenAIAuthEntry,
): Promise<void> {
let data: AuthData = {};
try {
data = JSON.parse(await readFile(authPath, "utf8")) as AuthData;
} catch (err) {
// 文件不存在视为空配置;其他解析错误必须抛出,防止静默清空其他账号
if (!isEnoentError(err)) {
throw err;
}
}
data.openai = updatedEntry;
const tmpPath = `${authPath}.tmp-${Date.now()}-${process.pid}`;
await writeFile(tmpPath, JSON.stringify(data, null, 2) + "\n", {
mode: 0o600,
});
await chmod(tmpPath, 0o600);
await rename(tmpPath, authPath);
}

/**
* 刷新 authData 并持久化(原地更新 access/refresh/expires/accountId)
* @returns null 表示成功;否则返回错误消息字符串
*/
async function tryRefreshOpenAIAuth(
authData: OpenAIAuthEntry,
refreshToken: string,
): Promise<string | null> {
try {
const tokenResponse = await refreshOpenAIToken(refreshToken);
const accountId =
extractAccountIdFromClaims(
tokenResponse.id_token ?? tokenResponse.access_token,
) ?? authData.accountId;
authData.access = tokenResponse.access_token;
authData.refresh = tokenResponse.refresh_token;
authData.expires = Date.now() + (tokenResponse.expires_in ?? 3600) * 1000;
if (accountId) {
authData.accountId = accountId;
}
// refresh token 已轮换,必须立即落盘,否则新 token 会永久丢失
await persistOpenAIAuth(OPENAI_AUTH_PATH, authData);
return null;
} catch (err) {
return err instanceof Error ? err.message : String(err);
}
}

/**
* 构造带重新登录提示的错误结果
*/
function reloginError(message: string): QueryResult {
return {
success: false,
error: `${message} — run \`opencode auth login openai\` to re-authenticate`,
};
}

// ============================================================================
// 格式化输出
// ============================================================================
Expand Down Expand Up @@ -213,13 +379,28 @@ export async function queryOpenAIUsage(
}

// 检查 OAuth token 是否过期
if (authData.expires && authData.expires < Date.now()) {
const expired = Boolean(authData.expires && authData.expires < Date.now());
const refreshToken = authData.refresh;

// 过期且没有 refresh token:无法刷新,维持原有提示
if (expired && !refreshToken) {
return {
success: false,
error: t.tokenExpired,
};
}

let refreshed = false;

// 已知过期:先刷新一次再查询(refresh token 会轮换,成功后立即落盘)
if (expired && refreshToken) {
const refreshError = await tryRefreshOpenAIAuth(authData, refreshToken);
if (refreshError) {
return reloginError(refreshError);
}
refreshed = true;
}

try {
const email = getEmailFromJwt(authData.access);
const usage = await fetchOpenAIUsage(authData.access);
Expand All @@ -228,6 +409,33 @@ export async function queryOpenAIUsage(
output: formatOpenAIUsage(usage, email),
};
} catch (err) {
// 401:access token 已失效,尝试刷新一次后重试(整个流程最多刷新一次)
if (
err instanceof HttpError &&
err.status === 401 &&
refreshToken &&
!refreshed
) {
const refreshError = await tryRefreshOpenAIAuth(authData, refreshToken);
if (refreshError) {
return reloginError(refreshError);
}
try {
const email = getEmailFromJwt(authData.access);
const usage = await fetchOpenAIUsage(authData.access);
return {
success: true,
output: formatOpenAIUsage(usage, email),
};
} catch (retryErr) {
return {
success: false,
error: retryErr instanceof Error ? retryErr.message : String(retryErr),
};
}
}

// 非 401 错误:维持原有错误传播
return {
success: false,
error: err instanceof Error ? err.message : String(err),
Expand Down
Loading