feat(agent): add credential refresh and unify learning tools

This commit is contained in:
2026-08-06 10:16:50 +08:00
parent 2dc37e3fd8
commit 258f4996eb
21 changed files with 1270 additions and 770 deletions
+48
View File
@@ -2,6 +2,7 @@ import { Router } from "express";
import { z } from "zod";
import { getAgentAuthContext } from "../auth/agentAuth.js";
import { type CredentialRefreshCoordinator } from "../auth/credentialRefresh.js";
import {
agentModelOptions,
isSupportedModel,
@@ -121,6 +122,7 @@ export const buildChatRouter = (
sessionTranscriptStore: SessionTranscriptStore,
learningOrchestrator: LearningOrchestrator,
resultReferenceResolver: ResultReferenceResolver,
credentialRefreshCoordinator: CredentialRefreshCoordinator,
) => {
const chatRouter = Router();
@@ -295,6 +297,16 @@ export const buildChatRouter = (
},
};
run.subscribers.add(subscriber);
const pendingCredentialRefresh =
credentialRefreshCoordinator.getPendingEvent(sessionRecord.sessionId);
if (pendingCredentialRefresh) {
subscriber.write(pendingCredentialRefresh.type, {
session_id: sessionRecord.sessionId,
request_id: pendingCredentialRefresh.requestId,
reason: pendingCredentialRefresh.reason,
timeout_ms: pendingCredentialRefresh.timeoutMs,
});
}
const cleanup = () => {
run.subscribers.delete(subscriber);
@@ -390,6 +402,7 @@ export const buildChatRouter = (
registerChatInteractionRoutes(chatRouter, {
activeRuns,
credentialRefreshCoordinator,
runtime,
sessionMetadataStore,
sessionUiStateStore,
@@ -803,6 +816,35 @@ export const buildChatRouter = (
logger.warn({ err: error, sessionId: clientSessionId }, "failed to persist chat stream state");
});
};
const unsubscribeCredentialRefresh = credentialRefreshCoordinator.subscribe(
binding.sessionId,
(event) => {
publish(event.type, {
session_id: clientSessionId,
request_id: event.requestId,
...(event.type === "credential_refresh_required"
? {
reason: event.reason,
timeout_ms: event.timeoutMs,
}
: {}),
...(event.type === "credential_refresh_failed"
? { message: event.message }
: {}),
});
},
);
const cancelCredentialRefreshOnAbort = () => {
credentialRefreshCoordinator.cancelSession(
binding.sessionId,
"credential refresh cancelled because the agent run was aborted",
);
};
abortController.signal.addEventListener(
"abort",
cancelCredentialRefreshOnAbort,
{ once: true },
);
try {
const preparedMessage = await buildPromptWithLearningContext(
@@ -925,6 +967,12 @@ export const buildChatRouter = (
logger.warn({ err: error, sessionId: clientSessionId }, "failed to persist chat stream state");
});
sessionBridge.finalizeRequest(clientSessionId);
abortController.signal.removeEventListener(
"abort",
cancelCredentialRefreshOnAbort,
);
credentialRefreshCoordinator.cancelSession(binding.sessionId);
unsubscribeCredentialRefresh();
activeRun.status = abortController.signal.aborted
? activeRun.status === "aborted"
? "aborted"