[PR #231] [CLOSED] fix(kiro): 优化 401 错误处理逻辑并修复健康检查错误 #311

Closed
opened 2026-02-27 07:18:55 +03:00 by kerem · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/justlovemaki/AIClient-2-API/pull/231
Author: @leonaii
Created: 1/14/2026
Status: Closed

Base: mainHead: main


📝 Commits (6)

📊 Changes

3 files changed (+220 additions, -27 deletions)

View changed files

📝 src/providers/claude/claude-kiro.js (+169 -17)
📝 src/providers/provider-pool-manager.js (+47 -10)
📝 static/app/i18n.js (+4 -0)

📄 Description

Pull Request: fix(kiro): 优化 401 错误处理逻辑并修复健康检查错误

📋 概述

优化 Kiro API 的 401 错误处理逻辑,在尝试刷新 token 前先刷新 UUID,并修复健康检查时的 Cannot read properties of undefined (reading 'length') 错误。

🐛 问题描述

  1. 401 错误处理不完善:当收到 401 错误时,直接尝试刷新 token,但没有更换 UUID,导致可能使用相同的身份标识重试
  2. 健康检查错误:点击 UI 上的"检查不健康"按钮时,Kiro 健康检查会尝试使用 contents 格式作为备用请求,但 Kiro 只支持 messages 格式,导致 Cannot read properties of undefined (reading 'length') 错误

变更内容

文件 变更说明
src/providers/provider-pool-manager.js 新增 refreshProviderUuid 方法,移除 Kiro 的 contents 格式备用请求
src/providers/claude/claude-kiro.js 新增 _refreshUuid 方法,修改 401 处理逻辑,添加 contents 格式支持

🔧 技术细节

1. ProviderPoolManager - 新增 refreshProviderUuid 方法

/**
 * 刷新指定提供商的 UUID
 * 用于在认证错误(如 401)时更换 UUID,以便重新尝试
 * @param {string} providerType - 提供商类型
 * @param {object} providerConfig - 提供商配置(包含当前 uuid)
 * @returns {string|null} 新的 UUID,如果失败则返回 null
 */
refreshProviderUuid(providerType, providerConfig) {
    // 生成新的 UUID 并更新 provider 状态
    // 同时更新 providerPools 中的原始数据
    // 自动保存到文件
}

2. ProviderPoolManager - 修复健康检查请求格式

修改前:

// Kiro OAuth 同时支持 messages 和 contents 格式
if (providerType.startsWith('claude-kiro')) {
    requests.push({ messages: [...], ... });
    requests.push({ contents: [...], ... }); // 错误:Kiro 不支持 contents 格式
    return requests;
}

修改后:

// Kiro OAuth 只支持 messages 格式
if (providerType.startsWith('claude-kiro')) {
    requests.push({ messages: [...], ... });
    return requests;
}

3. claude-kiro.js - 401 处理逻辑优化

修改前:

收到 401 → 尝试刷新 token → 失败则标记不健康

修改后:

收到 401 → 先刷新 UUID → 尝试刷新 token → 成功则用新 UUID 重试 → 失败则标记不健康
// Handle 401 (Unauthorized) - refresh UUID first, then try to refresh token
if (status === 401 && !isRetry) {
    console.log('[Kiro] Received 401. Refreshing UUID and attempting token refresh...');
    
    // 1. 先刷新 UUID
    const newUuid = this._refreshUuid();
    if (newUuid) {
        console.log(`[Kiro] UUID refreshed: ${this.uuid} -> ${newUuid}`);
        this.uuid = newUuid;
    }
    
    // 2. 尝试刷新 token
    try {
        await this.initializeAuth(true);
        console.log('[Kiro] Token refresh successful after 401, retrying request with new UUID...');
        return this.callApi(method, model, body, true, retryCount);
    } catch (refreshError) {
        console.error('[Kiro] Token refresh failed during 401 retry:', refreshError.message);
        // 3. 刷新失败,标记凭证不健康,让上层切换到其他凭证
        this._markCredentialUnhealthy('401 Unauthorized - Token refresh failed', refreshError);
        throw refreshError;
    }
}

4. claude-kiro.js - 添加 contents 格式支持(防御性修改)

// 处理不同格式的请求体(messages 或 contents)
let messages = body.messages;
if (!messages && body.contents) {
    // 将 Gemini 格式的 contents 转换为 messages 格式
    messages = body.contents.map(content => ({
        role: content.role || 'user',
        content: content.parts?.map(part => part.text).join('') || ''
    }));
}

if (!messages || !Array.isArray(messages) || messages.length === 0) {
    throw new Error('No messages found in request body');
}

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/justlovemaki/AIClient-2-API/pull/231 **Author:** [@leonaii](https://github.com/leonaii) **Created:** 1/14/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `main` --- ### 📝 Commits (6) - [`901b5ec`](https://github.com/justlovemaki/AIClient-2-API/commit/901b5ec8ea087a328e97ceb8cc0cf033e76b11d4) fix(i18n): 添加 credentialSwitchMaxRetries 配置项的中英文翻译 - [`499b974`](https://github.com/justlovemaki/AIClient-2-API/commit/499b974c65707c824c6a46103e653b09a936314d) Merge branch 'main' of https://github.com/leonaii/AIClient-2-API - [`6e65ba3`](https://github.com/justlovemaki/AIClient-2-API/commit/6e65ba3fa8d7df5537c25ca5ed7808131d854f63) fix(kiro): 增强401错误处理并支持Gemini格式请求体转换,修复健康KIRO健康检查错误。 - [`5a93f59`](https://github.com/justlovemaki/AIClient-2-API/commit/5a93f59c3be8da0116ad258660c2a38d1c6b4aab) Merge branch 'justlovemaki:main' into main - [`36d45df`](https://github.com/justlovemaki/AIClient-2-API/commit/36d45dfe477dd2e1409e6528a6e020be2c504235) Merge branch 'main' of https://github.com/leonaii/AIClient-2-API - [`f52e4b5`](https://github.com/justlovemaki/AIClient-2-API/commit/f52e4b56ac656a910479b89d04ddea61af7caeea) fix(kiro): 添加token刷新单例锁并增强JSON解析容错 ### 📊 Changes **3 files changed** (+220 additions, -27 deletions) <details> <summary>View changed files</summary> 📝 `src/providers/claude/claude-kiro.js` (+169 -17) 📝 `src/providers/provider-pool-manager.js` (+47 -10) 📝 `static/app/i18n.js` (+4 -0) </details> ### 📄 Description ## Pull Request: fix(kiro): 优化 401 错误处理逻辑并修复健康检查错误 ### 📋 概述 优化 Kiro API 的 401 错误处理逻辑,在尝试刷新 token 前先刷新 UUID,并修复健康检查时的 `Cannot read properties of undefined (reading 'length')` 错误。 ### 🐛 问题描述 1. **401 错误处理不完善**:当收到 401 错误时,直接尝试刷新 token,但没有更换 UUID,导致可能使用相同的身份标识重试 2. **健康检查错误**:点击 UI 上的"检查不健康"按钮时,Kiro 健康检查会尝试使用 `contents` 格式作为备用请求,但 Kiro 只支持 `messages` 格式,导致 `Cannot read properties of undefined (reading 'length')` 错误 ### ✨ 变更内容 | 文件 | 变更说明 | |------|----------| | `src/providers/provider-pool-manager.js` | 新增 `refreshProviderUuid` 方法,移除 Kiro 的 `contents` 格式备用请求 | | `src/providers/claude/claude-kiro.js` | 新增 `_refreshUuid` 方法,修改 401 处理逻辑,添加 `contents` 格式支持 | ### 🔧 技术细节 #### 1. ProviderPoolManager - 新增 `refreshProviderUuid` 方法 ```javascript /** * 刷新指定提供商的 UUID * 用于在认证错误(如 401)时更换 UUID,以便重新尝试 * @param {string} providerType - 提供商类型 * @param {object} providerConfig - 提供商配置(包含当前 uuid) * @returns {string|null} 新的 UUID,如果失败则返回 null */ refreshProviderUuid(providerType, providerConfig) { // 生成新的 UUID 并更新 provider 状态 // 同时更新 providerPools 中的原始数据 // 自动保存到文件 } ``` #### 2. ProviderPoolManager - 修复健康检查请求格式 **修改前:** ```javascript // Kiro OAuth 同时支持 messages 和 contents 格式 if (providerType.startsWith('claude-kiro')) { requests.push({ messages: [...], ... }); requests.push({ contents: [...], ... }); // 错误:Kiro 不支持 contents 格式 return requests; } ``` **修改后:** ```javascript // Kiro OAuth 只支持 messages 格式 if (providerType.startsWith('claude-kiro')) { requests.push({ messages: [...], ... }); return requests; } ``` #### 3. claude-kiro.js - 401 处理逻辑优化 **修改前:** ``` 收到 401 → 尝试刷新 token → 失败则标记不健康 ``` **修改后:** ``` 收到 401 → 先刷新 UUID → 尝试刷新 token → 成功则用新 UUID 重试 → 失败则标记不健康 ``` ```javascript // Handle 401 (Unauthorized) - refresh UUID first, then try to refresh token if (status === 401 && !isRetry) { console.log('[Kiro] Received 401. Refreshing UUID and attempting token refresh...'); // 1. 先刷新 UUID const newUuid = this._refreshUuid(); if (newUuid) { console.log(`[Kiro] UUID refreshed: ${this.uuid} -> ${newUuid}`); this.uuid = newUuid; } // 2. 尝试刷新 token try { await this.initializeAuth(true); console.log('[Kiro] Token refresh successful after 401, retrying request with new UUID...'); return this.callApi(method, model, body, true, retryCount); } catch (refreshError) { console.error('[Kiro] Token refresh failed during 401 retry:', refreshError.message); // 3. 刷新失败,标记凭证不健康,让上层切换到其他凭证 this._markCredentialUnhealthy('401 Unauthorized - Token refresh failed', refreshError); throw refreshError; } } ``` #### 4. claude-kiro.js - 添加 `contents` 格式支持(防御性修改) ```javascript // 处理不同格式的请求体(messages 或 contents) let messages = body.messages; if (!messages && body.contents) { // 将 Gemini 格式的 contents 转换为 messages 格式 messages = body.contents.map(content => ({ role: content.role || 'user', content: content.parts?.map(part => part.text).join('') || '' })); } if (!messages || !Array.isArray(messages) || messages.length === 0) { throw new Error('No messages found in request body'); } ``` --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
kerem 2026-02-27 07:18:55 +03:00
Sign in to join this conversation.
No labels
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/AIClient-2-API-justlovemaki#311
No description provided.