refactor: modularize portal server and harden session recovery

This commit is contained in:
john
2026-07-24 18:39:24 +08:00
parent 1d291fd528
commit 785731d98d
109 changed files with 29185 additions and 5836 deletions
+43
View File
@@ -34,6 +34,7 @@ import {
extractCurrentTurnImageUrls,
scrubConversationHistoricalImageAttachments,
} from './chat-image-turn-scope.mjs';
import { repairConversationToolHistory } from './chat-tool-history-repair.mjs';
import { buildVisionThumbnailBuffer } from './vision-image-thumb.mjs';
import {
memoryLimitForIntervention,
@@ -1663,6 +1664,47 @@ export function createTkmindProxy({
}
}
async function repairSessionToolHistory(sessionId) {
if (!sessionId) return { changed: false, updated: false };
const target = await resolveTarget(sessionId);
const upstream = await apiFetch(
target,
apiSecret,
`/sessions/${encodeURIComponent(sessionId)}`,
);
if (!upstream.ok) {
return { changed: false, updated: false, status: upstream.status };
}
const session = await upstream.json().catch(() => null);
const repair = repairConversationToolHistory(session?.conversation);
if (!repair.changed) return { ...repair, updated: false, status: upstream.status };
const update = await apiFetch(
target,
apiSecret,
`/sessions/${encodeURIComponent(sessionId)}`,
{
method: 'PUT',
body: JSON.stringify({ conversation: repair.conversation }),
},
);
if (!update.ok) {
const freshSessionRequired = update.status === 404 || update.status === 405;
const error = new Error(
freshSessionRequired
? '当前会话包含不完整的工具调用历史,需要迁移到新会话'
: `会话工具历史修复失败 (${update.status})`,
);
error.code = freshSessionRequired
? 'SESSION_TOOL_HISTORY_FRESH_SESSION_REQUIRED'
: 'SESSION_TOOL_HISTORY_REPAIR_FAILED';
error.retryable = !freshSessionRequired;
error.repairedConversation = repair.conversation;
throw error;
}
return { ...repair, updated: true, status: update.status };
}
async function prepareSessionReplyBody(
userId,
sessionId,
@@ -1691,6 +1733,7 @@ export function createTkmindProxy({
forceDeepReasoning,
});
await applySessionLlmProvider(sessionId);
await repairSessionToolHistory(sessionId);
const user = await userAuth.getUserById(userId);
if (!user) throw new Error('用户不存在');